Scaling API-first – The story of a global engineering organization
Introduction to java by priti sajja
1. Introduction to Java Programming
Unlocking the World of
Java Programming…..
June, 2011
Priti Srinivas Sajja
Visit pritisajja.info for detail
1 pritisajja.info
2. Unit 1: Course Content
• The Java programming language: history, evolution
• Introduction to the Java programming environment
– source programs organization,
– compilation to byte code,
– loading by the class loader,
– interpretation by the Java Virtual Machine,
– just-in-time compilation using HotSpot technology, tools
2 pritisajja.info
3. Unit 1: Course Content
• Key features of the Java platform:
– platform independence at source and byte code level,
– use of UNICODE character set,
– extensive use of reference types,
– automatic garbage collection, generics,
– assertions, collections and iterating over collections,
– event-driven programming for the GUI,
– security,
– out of box multithreading and networking,
– dynamic loading and linking of classes,
– interfaces, designed with the Internet in mind
• Packages, jar files, CLASSPATH, javadoc
• Different technologies under the Java umbrella
• The Java Development Kit, the Java Runtime Environment and IDEs
3 pritisajja.info
4. Unit 2: Java Programming - I
• Using the command line tools v/s an IDE, features of the IDE
• Syntax of the Java programming language
• An anatomy of a Java program
• Data types: primitive v/s reference types, wrapper classes,
automatic boxing and unboxing
• Interfaces, inheritance and polymorphism
• Exception handling
• Arrays
• Generics, assertions, enumerations
• The Java standard API
• String handling
• Java tools
4 pritisajja.info
5. Reference Book
• Schildt H. : The Complete Reference Java
2, 5th Edition, McGraw-Hill / Osborne,
2002
5 pritisajja.info
6. What is Java?
• Java is object-oriented with built in
Application Programming Interface
(API)
• It has borrowed its syntax from C/C++
• Java does not have pointers directly.
• Applications and applets are available.
6 pritisajja.info
7. Ideal Programming Language for Internet -- the objective was to share data
and documents across WWW invented in 1989.
To share interactive executable programs on WWW -- in 1990 Sun Micro
system has started project called Green using C++ for consumer electronic. The
team developed new programming language called ‘OAK’ .
OAK avoids dangerous things such as -- pointers and operator overloading. Also
they have added architecture neutrality and automatic memory management. The first web
browser called ‘WebRunner’ was developed using OAK. Afterword it is named as HotJava
OAK was renamed as java in 1995 --A common story is that the name Java relates to
the place from where the development team got its coffee.
7 pritisajja.info
8. Platform independence of Java
• Java is both compiled and interpreted.
• Source code is compiled to bytecode.
• The Java Virtual Machine (JVM) loads and
links parts of the code dynamically at run
time.
• Hence it carries substantial run time type
information on objects and supports late
binding.
8 pritisajja.info
9. Platform independence of Java Byte code
• Byte codes are the machine
language of the Java virtual
machine.
Java Byte Code • When a JVM loads a class
instruction … file, it gets one stream of
code … byte codes for each method
compiler in the class.
• The byte codes streams are
stored in the method area
of the JVM.
Host • The byte codes for a
system … method are executed when
that method is invoked
during the course of running
Java virtual Machine
the program.
• it has an instruction • They can be executed by
set interpretation, just-in-time
• it manipulates compiling, or any other
various memory technique that was chosen
areas at run time. by the designer of a
particular JVM.
9 pritisajja.info
10. Features of Java:
Simple • To follow
• Remote applets are not trusted and not allowed to use local
Secure resources
Object-oriented • Supports advantages of OOA
Platform independent • Independent form hardware and software platforms
and Architecture Neural
Interpreted • It is complied also and interpreted also.
• Java is strong, replacing pointer by reference and provides
Robust automatic memory management
Multi threaded • Supports concurrent procedures
Distributed and • Supports dynamic binding and links parts of code at the time
Dynamic of execution.
High performance • Java provides native language support
10 pritisajja.info
11. JDK : Java Development Kit
• The JDK is the Java Development Kit.
• Major versions are 1.1 (Java 1) and 1.2 (Java 2). (Version 1.3
has just been released.)
• This can be downloaded free of cost from http://java.sun.com
• The JDK can be downloaded for different platforms: Windows,
Unix (Solaris), MacOS.
• Comes as a self-extracting exe for Win95+, which extracts to
c:jdk1.2 directory.
• Certain environment variables, such as PATH and CLASSPATH
need to be set/reset.
• Path must be set to include c:jdk1.2bin
11 pritisajja.info
12. Java Utilities
• Javac
– The java compiler, that converts source code into byte
code stored in class files.
• Java
– The java interpreter that executes byte code for a java
application from class files.
12 pritisajja.info
13. Using the JDK: Hello World Application
Step 1: Write java code
/**
The HelloWorld class implements an application that
simply displays “Hello World!” to the standard output
(console)
*/
public class HelloWorld
{
public static void main (String args[])
{
//required prototype for main function
System.out.println(“Hello world!”);
} // end of main
…………………………………………..
}// end of class
………………………………………………...
13 pritisajja.info
14. Using the JDK: Hello World Application
Step 2: Save the source in a file
• The file MUST have the same name as the public class in the
source, and must have a .java extension. That is, the above file
should be saved as
HelloWorld.java
with the case maintained.
• A java source file cannot contain more than one public class
according to the above restriction.
How many main methods can be there in a java program?
14 pritisajja.info
15. Using the JDK: Hello World Application
Step 3: Compile the source file using javac
• Use the following command line at the shell prompt
javac HelloWorld.java
• If the code is correct, compilation will produce the file
HelloWorld.class
• If there are errors, repeat steps 1-3.
what javac does behind the scenes, use the following
command line javac -verbose HelloWorld.java.
15 pritisajja.info
16. Using the JDK: Hello World Application
Step 4: Run the compiled code.
• Invoke the java interpreter by the command line
java HelloWorld
• Output: Hello World!
16 pritisajja.info
17. Naming Conventions
• Java distinguishes between UPPER and lower case variables.
• The convention is to capitalize the first letter of a
class name.
• If the class name consists of several words, they are run together
with successive words capitalized within the name (instead of using
underscores to separate the names).
• The name of the constructor is the same as the
name of the class.
• All keywords (words that are part of the language and cannot
be redefined) are written in lower case.
17 pritisajja.info
18. Prototype of the main method
public static void main (String args[])
For the main method
• public is the access specifier.
• static is the storage class.
• void is the return type.
• String args[ ] is an array of strings
Check public static void main( ) ? Will it cause any
error? If yes, what?
18 pritisajja.info
19. About main method…
• Several main methods can be defined in a java class.
• The interpreter will look for a main method
with the prescribed signature as the entry point.
• A method named main, which has some other signature is of
no particular significance. It is like any other method
• in the class.
• Therefore, if the main method is not declared correctly, the
application will not execute. There may not be any compilation
problem.
• This class will compile correctly, but will not execute. The interpreter
will say
In class NoMain: void main (String argv[]) is not defined
19 pritisajja.info
20. public class TwoMains
{
/** This class has two main methods with * different signatures */
public static void main (String args[])
{
//required prototype for main method
System.out.println(“Hello world!”);
int i;
i = main(2);
System.out.println (“i = ” + i );
}
/**This is the additional main method*/
public static int main(int i)
{ return i*i; }
} // end of class PSS
20 pritisajja.info
21. Is it true?
• The argument to the mandatory main
function
public static void main (String args[])
which is String args []
can also be written as
String [] args
21 pritisajja.info
22. Comments
There are three types of comments defined by Java.
1. Single-line comment :Java single line comment
starts from // and ends till the end of that line.
2. Multiline comment: Java multiline comment is
between /* and */.
3. Documentation comment : Documentation comment
is used to produce an HTML file that documents your
program. The documentation comment begins with a
/** and ends with a */.
22 pritisajja.info
23. Identifiers
• Identifiers are used for class names, method names,
and variable names.
• An identifier may be any sequence of uppercase and
lowercase letters, numbers, or the underscore and
dollar-sign characters.
• Identifiers must not begin with a number.
• Java Identifiers are case-sensitive.
• Some valid identifiers are ATEST, count, i1, $Atest, and
this_is_a_test
• Some invalid identifiers are 2count, h-l, and a/b
23 pritisajja.info
24. Operators
Java operators can be grouped into the following four groups:
• Arithmetic,
• Bitwise,
• Relational,
• Logical.
24 pritisajja.info
26. Bitwise Operators
Operator Result
• ~ Bitwise unary NOT
• & Bitwise AND
• | Bitwise OR
• ^ Bitwise exclusive OR
• >> Shift right
• >>> Shift right zero fill
• << Shift left
• &= Bitwise AND assignment
• |= Bitwise OR assignment
• ^= Bitwise exclusive OR assignment
• >>= Shift right assignment
• >>>= Shift right zero fill assignment
• <<= Shift left assignment
26 pritisajja.info
27. Relational Operators
Operator Result
• == Equal to
• != Not equal to
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to
27 pritisajja.info
28. Boolean Logical Operators
Operator Result
• & Logical AND
• | Logical OR
• ^ Logical XOR (exclusive OR)
• || Short-circuit OR
• && Short-circuit AND
• ! Logical unary NOT
• &= AND assignment
• |= OR assignment
• ^= XOR assignment
• == Equal to
• != Not equal to
• ? : Ternary if-then-else
28 pritisajja.info
29. Boolean Logical Operators
Operator Result
• & Logical AND
• | Logical OR
• ^ Logical XOR (exclusive OR)
• || Short-circuit OR
• && Short-circuit AND
• ! Logical unary NOT
• &= AND assignment
• |= OR assignment
• ^= XOR assignment
• == Equal to
• != Not equal to
• ? : Ternary if-then-else
29 pritisajja.info
30. Data Types
• Three kinds of data types in Java.
– primitive data types
– reference data types
– the special null data type, also the type of
the expression null. (only possible value is
null) We may write if (obj!= null).
30 pritisajja.info
31. Primitive Data Types in Java
type kind memory range
byte integer 1 byte -128 to 127
short integer 2 bytes -32768 to 32767
int integer 4 bytes -2147483648 to 2147483647
-9223372036854775808 to
long integer 8 bytes
-9223372036854775807
±3.40282347 x 1038 to
float floating point 4 bytes
±3.40282347 x 10-45
±1.76769313486231570 x 10308 to
double floating point 8 bytes
±4.94065645841246544 x 10-324
single
char character
2 bytes all Unicode characters
boolean true or false 1 bit
There is no unsigned integer in java.
31 pritisajja.info
32. /** This program demonstrates how Java
* adds two integers. */
public class BigInt
{
public static void main(String args[])
{
int a = 2000000000; //(9 zeros)
int b = 2000000000;
System.out.println ( “This is how Java adds integers”);
System.out.println ( a + “+” + b + “ = ” + (a+b) );
} // end of main
}// end of class
Output:
This is how Java adds integers
2000000000 + 2000000000 = -294967296
32 pritisajja.info
33. public class Significant
{
public static void main (String args[])
{
final float PI = 3.141519265359f;
float radius = 1.0f;
float area;
area = PI * radius * radius;
System.out.println (“The area of the circle = ” +
area);
}// end of main
}// end of class
Output:
area of the circle = 3.1415193
33 pritisajja.info
34. Declaration of variable
• A variable is defined by an identifier, a type, and an
optional initializer.
• The variables also have a scope(visibility / lifetime).
• In Java, all variables must be declared before they can
be used. The basic form of a variable declaration is :
type identifier [ = value][, identifier
[= value] ...] ;
• Java allows variables to be initialized dynamically. For
example: double c = 2 * 2;
34 pritisajja.info
35. Scope and life of a variable:
• Variables declared inside a scope are not
accessible to code outside.
• Scopes can be nested. The outer scope
encloses the inner scope.
• Variables declared in the outer scope are
visible to the inner scope.
• Variables declared in the inner scope are
not visible to the outside scope.
35 pritisajja.info
36. public class Main
{ public static void main(String args[])
{ int x; // known within main
x = 10;
if (x == 10)
{ int y = 20;
System.out.println("x and y: " + x + " " + y);
x = y + 2; }
PSS
System.out.println("x is " + x);
}// end of main
}// end of class
Output:
x and y: 10 20
x is 22
36 pritisajja.info
37. public class Main2
{ public static void main(String args[])
{ if (true)
{ int y = 20;
System.out.println("y: " + y);
} // end of if
y = 100;
}// end of main
}// end of class
PSS
37 pritisajja.info
38. public class Main3
{ public static void main(String args[])
{ int i = 1;
{int i = 2;
}
} PSS
}
38 pritisajja.info
39. Flow Control: if:
• if(condition) statement;
• Note: Write a java program that compares two
variables and print appropriate message.
• The condition can be expression that result in a
value.
• Expression may return boolean value.
• if (b) is equivalent to if (b== true).
39 pritisajja.info
40. Flow Control: if else:
if (condition) statement1;
else statement2;
• Each statement may be a single statement or a
compound statement enclosed in curly braces (a
block).
• The condition is any expression that returns a
boolean value.
• Nested if statements are possible
40 pritisajja.info
41. Flow Control: if else ladder:
PSS
if(condition) statement; Example
else if(condition) statement; public class Main4
else if(condition) statement; { public static void main(String args[])
… { int month = 4;
… String value;
else statement; if (month == 1) value = "A";
else if (month == 2) value = "B";
else if (month == 3) value = "C";
else if (month == 4) value = "D";
else value = "Error";
System.out.println("value = " + value);
}}
41 pritisajja.info
42. Switch statement:
switch (expression)
{ case value1: statement sequence
break;
case value2 : statement sequence
break;
...
case valueN: statement sequence
break;
default: default statement sequence }
. Switch statement can be nested
42 pritisajja.info
43. Command Line arguments
public class LeapYear
{ public static void main(String[] args)
{ int year = Integer.parseInt(args[0]);
boolean Leap;
Leap= (year % 4 == 0);
if ((Leap) && (year!=100))
System.out.println(Leap); PSS
}
43 } pritisajja.info
44. Command Line arguments
public class PowersOfTwo
{ public static void main(String[] args)
{ int N = Integer.parseInt(args[0]);
int i = 0;
int powerOfTwo = 1;
while (i <= N)
{ System.out.println(i + " " + powerOfTwo);
powerOfTwo = 2 * powerOfTwo;
i = i + 1; }
PSS
}
}
44 pritisajja.info
45. Command Line arguments
public class Sqrt
{ public static void main(String[] args)
{ double c = Double.parseDouble(args[0]);
double epsilon = 1e-15;
double t = c; // relative error tolerance
while (Math.abs(t - c/t) > epsilon*t)
{ t = (c/t + t) / 2.0; }
// print out the estimate of the square root of
System.out.println(t);
} PSS
}
45 pritisajja.info
46. Recursion
PSS
class factorial{
int fact(int n){
if (n==1) return 1;
else return (n*fact(n-1));}
}
class factdemo{
public static void main (String args[]){
int a = 4; int fa=0;
factorial f = new factorial ();
fa=f.fact(a);
System.out.println(fa);
}
}
46 pritisajja.info
47. Fibonacci
PSS
class fibonacci {
int fibo(int n){
if (n==1) return 1;
else return ( fibo(n-1) + fibo(n-2) ); }
}
class fibodemo{
public static void main (String args[]){
int a = 3; int fa=0;
fibonacci f = new fibonacci ();
fa=f.fibo(a);
System.out.println(fa);
}
}
47 pritisajja.info
48. Arrays
• General form of one dim array declaration is
type array-name[size];
• Examples are:
• int a[10];
– Defines 10 integers such as a[0], a[1], … a[9]
• char let[26];
– Defines 26 alphabets let[1]=„B‟;
• float x[20];
• Employee e[100]; //Employee is a class definition
• Tree t[15]; // Tree is a class
48 pritisajja.info
49. Array Definition with Initialization
• int maxmarks[6]= {71,56,67,65,43,66}
• char let[5]= {„a‟, „e‟, „I‟, ‟o‟, ‟u‟};
• Initialization of an array can be done using
new statement as follows:
– int a[j]; // defines a as an array contains j integrs
– a=new int [10] // assigns 10 integers to the array a
• This can also be written as
– int [] a = new int [10];
49 pritisajja.info
50. Example of array
PSS
class array{
public static void main (String args[ ]){
int score [] = { 66,76,45,88,55,60};
for (int i=0; i<6; i++)
System.out.println(score[i]);
System.out.println(“==============”);
}
}
50 pritisajja.info
51. Example of array
public class Main4 { PSS
public static void main(String[] args)
{ int[] intArray = new int[] { 1, 2, 3, 4, 5 };
// calculate sum
int sum = 0;
for (int i = 0; i < intArray.length; i++)
{ sum = sum + intArray[i]; }
// calculate average
double average = sum / intArray.length;
System.out.println("average: " + average);
}
}
51 pritisajja.info
52. Example of array
PSS
public class Main6
{ public static void main(String args[])
{ int a1[] = new int[10];
int a2[] = {1, 2, 3, 4, 5};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
52 pritisajja.info
53. Example of array with functions
PSS
class ArrayPass {
void printing(int s[]){
int i=0;
for (i=0; i<6; i++)
System.out.println(s[i]);
System.out.println("=============");
}
}
class arraydemo{
public static void main (String args[ ]){
ArrayPass student = new ArrayPass();
int score[] = {66,76,45,88,55,60};
student.printing(score);
}
}
53 pritisajja.info
54. import java.util.*;
public class array{
public static void main(String[] args){
int num[] = {50,20,45,82,25,63};
int l = 6; // you may use l= num.length;
int i,j,t;
System.out.print("Given number : ");
for (i = 0;i < l;i++ ) { System.out.print(" " + num[i]); }
System.out.println("n");
System.out.print("Accending order number : ");
Arrays.sort(num);
for(i = 0;i < l;i++){
System.out.print(" " + num[i]);
}
}
}
54 pritisajja.info
55. Two Dimensional Arrays
Declaration of a two dimensional array
called twoD with size 4*5
• int twoD[][] = new int[4][5];
(0,0) (0,3) (0,4)
(1,0) (1,1) (1,4)
(2,0) (2,2) (2,4)
(3,0) (3,3) (3,4)
55 pritisajja.info
56. Matrix
public class Main {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
for (int i = 0; i < 4; i++)
{ for (int j = 0; j < 5; j++)
{ twoD[i][j] = i*j; } }
//--------------------------------------------------------------------------------
for (int i = 0; i < 4; i++)
{ for (int j = 0; j < 5; j++)
{ System.out.print(twoD[i][j] + " "); }
System.out.println(); }
}
}
56 pritisajja.info
58. Three Dimensional Array
public class Main {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
for (int k = 0; k < 5; k++)
threeD[i][j][k] = i * j * k;
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < 4; j++)
{ for (int k = 0; k < 5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println(); }
System.out.println(); }
} }
58 pritisajja.info
59. Jagged array
• When you allocate memory for a multidimensional array, you can
allocate the remaining dimensions separately. For example, the
following code allocates the second dimension manually.
public class Main {
public static void main(String[] argv)
{ int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5]; } }
59 pritisajja.info
60. public class Main {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
60 pritisajja.info
61. for (int i = 0; i < 4; i++)
{ for (int j = 0; j < i + 1; j++)
{ twoD[i][j] = i + j; } }
//---------------------------------------------
for (int i = 0; i < 4; i++)
{ for (int j = 0; j < i + 1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println(); }
}
}
61 pritisajja.info
63. Bank constructor
class Bank {
int accno;
String accname;
float accbal;
Bank()
{accno=999;
accname= "XXX";
accbal= 0;}
Bank(int x, String y, float z)
{accno=x;
accname= y;
accbal= z;}
Bank(int x, String y)// default t constructor
{accno=x;
accname= y;
accbal= 1000;}
void printbal()
{ System.out.println (accno);
System.out.println ( accname );
System.out.println (accbal);
}
63}// end of class pritisajja.info
64. Bank constructor
class BankDemo {
public static void main (String args[ ]){
Bank b1= new Bank();
Bank b2 = new Bank(123, "PSS");
Bank b3 = new Bank (124, "XYZ", 5000);
b1.printbal();
b2.printbal();
b3.printbal();
}
}
64 pritisajja.info
65. Bank with methods and array
class Bank { void printbal()
int accno; { System.out.println (accno);
String accname; System.out.println ( accname );
float accbal; System.out.println (accbal);
Bank() System.out.println("----------------------------------");
{accno=999; }
accname= "XXX";
accbal= 0;} void deposit(float Amt)
Bank(int x, String y, float z)
{ System.out.println("Depositing ....."+ Amt);
{accno=x;
accbal=accbal + Amt; }
accname= y;
accbal= z;}
Bank(int x, String y)
{accno=x; void withdraw(float Amt)
accname= y; { System.out.println("Withdrwing ....."+ Amt);
accbal= 1000;} accbal=accbal - Amt; }
}// end of class
65 pritisajja.info
66. Bank Calling Class
class BankDemo3 {
public static void main (String args[ ]){ b[2].withdraw(15000);
b[2].printbal();
Bank [] b = new Bank[3];
}
b[0]= new Bank(); }
b[0].printbal();
b[1]= new Bank(111, "PPP", 5000);
b[1].printbal();
b[2]= new Bank(222,"SSS", 10000);
b[2].printbal();
b[2].deposit (10000);
b[2].printbal();
66 pritisajja.info
67. Home Assignment
• Consider students class as follows:
– Sno integer
– Sname String
– Marks 6 integers
• Write java class having the above Student structure.
Define method for total, average and result printing in
this class. Define a main class, having an array of 3
students. Use the developed utilities for these 3
students.
67 pritisajja.info
68. Strings
• Strings in java are not primitive data types
but members of String class.
• + operator can be used to join two strings.
68 pritisajja.info
70. Strings
• Strings in java are not primitive data types
but members of String class.
• + operator can be used to join two strings.
70 pritisajja.info