Professional Documents
Culture Documents
Unit-ii
History of java: Java was developed by team of
James Gosling, Patrik Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc in 1991.
Contd.. It was started as a project named Green, to develop a platform-independent language that can be used to create software to be installed in various consumer electronic devices, such as microwave ovens and remote controls etc.
. Different electronic devices will use different types of processors as controllers. It is possible to compile a C/C++ program for any type of processor, but requires a full C/C++ compiler for that processor. Compilers are expensive and time-consuming to create.
Contd..
Gosling and others began work to create platform independent language that could be used to produce code that would run on a variety of processors. Challenging, because consumer devices are controlled by many different chips (processors). Programs were translated first into an intermediate code ( java byte code ) common to all devices processors. Then the intermediate code was translated into the machine language code for a particular device processor by using Java Virtual Machine ( JVM).
Contd..
Java programs require a Java Virtual Machine to run. The Java Virtual Machine is written in C and C++, and has been ported to many devices, including desktop computers running Windows and Mac OS X, to high-end servers running Solaris and Linux, and to mobile phones.
Contd..
The Green project ran into some difficulties. The marketplace for consumer-electronic devices was not developing in the early 1990s as quickly as Sun had anticipated. The project was in danger of being canceled. Luckily, by god grace, the World Wide Web gained popularity in 1993. The Sun people saw the immediate possibility of using Java to add dynamic content, such as interactivity and animations, to Web pages. This gave new life to the project.
The name Java was chosen because the creators of the language often discussed ideas for the language at a local coffee shop.
Java Terminology
Java Virtual Machine (JVM) It tells machine architecture using Java Virtual Machine Specifications. Java Runtime Environment (JRE)
A runtime environment which implements Java Virtual Machine, and provides java Packages Classes (like util, math, lang, awt,swing etc) necessary to execute Java programs. This is the software on your computer that actually runs Java programs.
Java Development Kit (JDK) JDK contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Appletviewer, etc
Java Platforms
There are three main platforms for Java: Java SE (short for Standard Edition) runs on
desktops and laptops.
java.exe ( JRE)
Setting on windows xp
Those we have installed oracle 10g on your machine update the system path variable as shown below.
Whatever is there in user path variable copy into the system path variable.
Week 3 :
a) Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome. b) Write a Java program for sorting a given list of names in ascending order. c) Write a Java program to make frequency count of words in a given text.
For example, in C/C++ you can assign a floating-point value to an integer. In Java, you cannot.
Java keywords
Data Types
The Simple Types
Java defines eight simple (or elemental) data types : byte, short, int, long, char, float, double, and boolean. These can be put in four groups: Integers -This group includes byte, short, int, and long Floating-point numbers - This group includes float and double Characters - This group includes char Boolean -This group includes boolean
integer types
Java does not support unsigned integers. All are signed, positive and negative values.
Width 64 32 16 8
Range
byte
The smallest integer type is byte. Variables of type byte are especially useful while working with a data from a network or file. Byte variables are declared by using the byte keyword.
Ex:byte b, c;
Floating-Point Types
There are two kinds of floating-point types. All math functions, such as sin( ), cos( ), and sqrt( ), return double values. Name
double float
Width in Bits
64 32
Approximate Range
4.9e324 to 1.8e+308 1.4e045 to 3.4e+038
Characters
In C/C++, char is an integer type that is 8 bits wide. Java uses Unicode to represent characters. Unicode can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. Hence it requires 16 bits. The range of a char in java is 0 to 65,536. There are no negative chars. The first 128 characters of Unicode are same as that of ASCII code.
} }
Booleans
It can have only one of two possible values, true or false.
Operators
Arithmetic Operators
Operator + * / % += = *= /= %= ++ Result Addition Subtraction (also unary minus) Multiplication Division Modulus Addition assignment Subtraction assignment Multiplication assignment Division assignment Modulus assignment Increment Decrement
The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types. No fractional component attached to the result, when the division operator is applied to an integer type. The modulus operator, %, returns the remainder of a division operation. It can be applied to floating-point types as well as integer types.
Ex:int x = 42; double y = 42.25; x mod 10 = 2 y mod 10 = 2.25
Relational Operators
The result of relational operation is a boolean value
Operator
== != > < >= <=
Result
Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to
Note :int done; // ... if( !done ) ... if( done ) ... Valid in C/C++ , but not in java
In Java, these statements must be written like this: if(done == 0)) ... // This is Java-style. if(done != 0) ...
In C/C++, true is any nonzero value and false is zero. In Java, true and false are nonnumeric values which do not relate to zero or nonzero.
Operator
! & | ^ || && &= |= ^= ?:
Result
Logical unary NOT Logical AND Logical OR Logical XOR (exclusive OR) Short-circuit OR Short-circuit AND AND assignment OR assignment XOR assignment Ternary operator
Java provides two interesting Boolean operators not found in many other languages. These are secondary versions of the Boolean AND and OR operators.
These are known as short-circuit logical operators. The OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is.
If you use the || and && forms, Java will not bother to evaluate the right-hand operand when the outcome of the expression can be determined by the left operand alone. This is very useful when the right-hand operand depends on the result of the left one in order to function properly.
?: Ternary operator
General form:
expression1 ? expression2 : expression3 ;
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.
Operator
~ & | ^ << >> >>>
Result
Bitwise unary NOT Bitwise AND Bitwise OR Bitwise exclusive OR Shift left Shift right Shift right zero fill
Cotnd.. &= |= ^= <<= >>= >>>= Bitwise AND assignment Bitwise OR assignment Bitwise exclusive OR assignment Shift left assignment Shift right assignment Shift right zero fill assignment
var = expression;
Here, the type of var must be compatible with the type of expression. It allows you to create a chain of assignments.
int x, y, z; x = y = z = 100; // set x, y, and z to 100
low
Constants
Integer constants
Decimal values without a fractional component.
3 types
Base 10 constants ( decimal numbers )
The range of decimal digit is 0 to 9, ex:- 2
Default int constant size is 32 bits Long int constants are specified by appending an upperor lowercase L to the constant. Ex:- 0xfffffffffffffL, 6893468939L .
Floating-Point constants
Decimal values with a fractional component. Representation
Standard notation , ex:- 2.0, 3.14159 Scientific notation ex:- 6.022E23, 314159E05, 2e+100.
Floating-point constants in Java default to double precision. To specify a float constant, you must append an F or f to the constant.
Ex:- 3.14f
Boolean Constants
There are only two logical values that a boolean value can have, true and false. Only in lower case.
Character constants
A character constant is represented inside a pair of single quotes. All of the visible unicode characters can be directly entered inside the quotes, such as a, z, and @. For characters that are impossible to enter directly, there are several escape sequences, which allow you to enter the character you need. Ex:- \ for the single-quote character itself, and \n for the newline character.
Description
Single quote Double quote Backslash New line (also known as line feed) Tab Backspace
String Constants
Sequence of characters between a pair of double quotes. Examples of string literals are
Hello World two\nlines \This is in quotes\
A string constant must begin and end on the same line. In java strings can be concatenated by using + operator.
Ex:- wel + come ;
Variables
Declaring a Variable
In Java, all variables must be declared before they can be used. Like in c++ , variable can be declared anywhere in the program. Syntax:type identifier [ = value];
Control Statements
Javas control statements can be put into the following categories: selection iteration jump
Switch( expression )
Same as in c/c++. The expression must be of type byte, short, int, long or char; Each case value must be a constant, not a variable.
Iteration Statements
Javas iteration statements are
for while do-while.
Syntax is similar to c/c++. The condition is any expression that returns a boolean value.
For-Each Version of the for Loop Syntax: for( type itr-var : collection ) { Statement block; }
Jump Statements
Java supports three jump statements: break, continue, and return. 1. In Java, the break statement has three uses. First, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a advanced form of goto.
Syntax
label : ------break label; Notice that the label must precede the outermost loop out of which you want to come out. It also must be followed by a colon. Java does not have goto statement
Ex:// Using break as a advanced form of goto. class Break { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; // break out of second block System.out.println("This won't execute"); } System.out.println("This won't execute"); } System.out.println("This is after second block."); } } }
Ex:2
// Using break to exit from nested loops
class BreakLoop4 { public static void main(String args[]) { outer: for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++) { if(j == 10) break outer; // exit both loops System.out.print(j + " ");
2. continue
Similar to c/c++
3. return
The return statement is used to explicitly return from a method.
Arrays
Note :- Arrays creation in Java is different from c/c++. One- Dimensional Arrays :-
Method-I
int month_days[ ]; month_days =new type[ size];
Method II
int month_days[ ]=new type[ size ];
We can obtain the length of an array by using length property. ex:- int x[ ]=new int[5]; int len=x.length; length is 5 Default values of an array are zeros. Direct initialization int x[ ]={ 1,2,3 };
Method-I
int twoD[ ][ ]; month_days =new type[ row_size][ col_size];
Method II
int twoD[ ]=new type[ row_size ][ col_size];
When you allocate memory for a multidimensional array, you need to specify the memory for the first (leftmost) dimension only. We can allocate the remaining dimensions separately.
Ex: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];
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];
{ 1,2,3 }, {4,5,6,7 }
Same
boolean
Six solid arrows denote conversions without information loss. Dotted arrows denote conversions that may lose information. For example, a large integer such as 123456789 has more digits than the float type can represent. When the integer is converted to a float, the resulting value has the correct magnitude, but it loses some precision. Ex : int n=123456789; float f=n; // 1.23456792E8;
Lifetime
The lifetime of a declared element is the period of time during which the element exists during execution
void f1() {
int x=1,y=2; int c=x+y; System.out.println(c);
} }
{
int x=1,y=2; int c=x+y; System.out.println(c);
// Demonstrate block scope. class Scope { public static void main(String args[]) {
int x;
// known to all code within main
x = 10; if(x == 10) // start new scope { int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y); x = y * 2; } // y = 100; // Error! y not known here
// x is still known here.
} } Scope and life time of x is limited to main method block ( including if block ). Scope and lifetime of y is limited to if block only.
Note : In C++, it is possible to redefine a variable inside a nested block. The inner variable hides the outer one. This can be a source of programming errors; hence, Java does not allow it.
// This program will not compile class ScopeErr { public static void main(String args[ ]) { int x = 1; { // creates a new scope int x = 2; // Compile-time error x already defined! } } }
Ex:public class ClassName { public static void main(String args[] { statement1 statement2 . . . statementN } }
public indicates it is visible from any point of the program. static is to call the method without creating an instance of the start class. void indicates, it does not return anything. String arg[ ] is to take the data from command prompt.
Compiler
Source Code
0101010 1011001 0100101 Java Virtual 0100100 Machine 1010100 1001010 OR 1001010 JRE 10010 Java Byte Code
The data, or variables, defined within a class are called instance variables. Functions defined within a class are called methods. The methods and variables defined within a class are called members of the class.
Note:The class declaration and the implementation of the methods should be within the class.
Declaring Objects
Ex:class Box {
double width; double height; double depth;
}
Box mybox = new Box();
Constructors
A constructor initializes an object immediately upon creation. It has the same name as the class name and is syntactically similar to a method. Constructors do not have any return type, not even void.
class Box { double width; double height; double depth; Box() { width = 10; height = 10; depth = 10; } }
Parameterized Constructors
In the previous example, all boxes have the same dimensions. Parameterized constructor are used to construct Box objects of various dimensions.
class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } }
Contd..
this can be used to resolve any name collisions that might occur between instance variables and local variables.
Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }
Overloading Methods
Two or more methods with same name can be declared in the same class, as long as they have different sets of parameters (determined by the number, types and order of the parameters) This process is called method overloading. Java uses the number or type or order of parameters to determine which version of the overloaded method to call. We can not overload a method based on return type.
Ex :
void println( ) void println( boolean x ) void println( char x ) void println( char[ ] x ) void println( double x ) void println( float x) void println( int x ) void println( long x) void println( String x)
Ex :
class OverloadDemo {
void test ( ) { System.out.println("No parameters"); } void test ( int a ) { System.out.println("a: " + a); } void test ( int a, int b ) { System.out.println("a and b: " + a + " " + b); } double test (double a) { System.out.println("double a: " + a); return a*a; }
Overloading Constructors
Constructors can be overloaded.
class Box { double width; double height; double depth; Box ( ) { width = 10; height =15; depth = 20; } Box (double w, double h, double d ) { width = w; height = h; depth = d; }
Parameter Passing
There are two common ways that a computer language can pass a parameter to a method.
Call-by-value
The call-by-value copies the value of a actual parameter into the formal parameter of the method. In this method, changes made to the formal parameter of the method have no effect on the actual parameter.
// Simple types are passed by value. class Test { void meth(int i, int j) { i *= 2; j /= 2; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
} } The output from this program is shown here: a and b before call: 15 20 a and b after call: 15 20
Call-by-reference
In call-by-reference, a reference to an actual parameter (not the value of the argument) is passed to the formal parameter. In this method, changes made to the formal parameter will affect the actual parameter used to call the method.
Simple types, int, float,char,double, are passed by value. Objects are passed by reference ( including arrays and Strings )
// Objects are passed by reference. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // pass an object void meth(Test o) { o.a *= 2; o.b /= 2; } } class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } } This program generates the following output: ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10
Recursion
Recursion is the process of defining something in terms of itself. A method that calls itself is called a recursive method.
Ex:class Factorial { int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } }
Understanding static
Normally, the word static means unchanging. In java, the value of the static instance variable can change. For example, you can create a static instance variable, and then assign values to it as a program executes.
Its used to describe a special type of instance variable or method that isnt associated with a instance of a class. Instead, static instance variable and methods are associated with the class itself. That means you dont have to create an instance of the class to access a static instance variables or methods. Instead, you access a static instance variable or method by specifying the class name, not a variable that references an object.
Methods declared as static have several restrictions while accessing instance members :
They can only call other static methods. They can only access static instance variables. this or super should not be used in static methods.
Common uses
To keep a count of how many instances of a class have been created. To maintain a serial number thats assigned to each new instance.
For example, a student class might maintain a static field that holds the serial number that is assigned to the next Student object created from the class.
Syntax :
class class_name
{ access specifier static type variable;
:
access specifier static type fun_name() { }
:
}
Note :
Use of static keyword in a method is an error. In other words, class members can be static, but local variables cant.
Syntax :
Ex :
static {
statement1; statement2
. . }
This example is pretty simple. In fact, we can achieve the same effect by assigning 32 to the variable when it is declared.
However,
Suppose, if you had to perform a complicated calculation to determine the value of x, or Suppose its value comes from a database. In that case, a static initializer/block can be very useful.
final
A variable which is declared as final can not be modified latter. This means that you must initialize a final variable when it is declared. Ex:final float pi=3.14 ; final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5;
Inner Classes
An inner class is a class thats declared inside of another class.
Ex :
class Outer {
int outer_x = 100; void test() { Inner inner = new Inner(); inner.display();
}
class Inner {
void display() { System.out.println("display: outer_x = " + outer_x);
} } }
class InnerClassDemo { public static void main(String args[ ]) { Outer outer = new Outer(); outer.test(); } }
Output
display: outer_x = 100
An inner class automatically has access to all the members of the outer class ( directly ) even private members. The outer class can not access members of inner class directly. An inner class is fully within the scope of outer class. Therefore , the outer class can instantiate inner class. Any code out side of outer class can not instantiate inner class.
String Class
The String class supports several constructors. String is an object not an array of characters in java. Once a String object is created, you cannot change the characters that are in string. Strings created by a StringBuffer class can be modified after they are created. Both the String and StringBuffer classes are defined in java.lang package
Constructors
String s = new String(); // Creates an empty string. String s=new String( char chars[ ] ) String( char chars[ ], int startIndex, int numChars)
Ex :
char chars[ ] = { 'a', 'b', 'c' }; String s = new String(chars);
Ex :
char chars[ ] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3);
char charAt(int index) boolean equals(Object anotherObject) int compareTo(Object anotherObject) boolean endsWith(String suffix) boolean startsWith(String prefix)
compareTo( )
A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. Value
Less than zero Greater than zero Zero
Meaning
The invoking string is less than str. The invoking string is greater than str. The two strings are equal.
Garbage Collection
Objects are dynamically allocated by using the new operator. In C++, dynamically allocated objects must be manually released by use of a delete operator. Java handles deallocation automatically. This technique is called garbage collection.
Technique
when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.
Garbage collection only occurs at regular intervals during the execution of your program.
Private:
A private member is accessible only to the class in which it is defined. Inheritance does not apply on the private members. They are Just like secrets. Use private keyword to create private members.
Protected:
Allows the class itself, subclasses, and all classes in the same package to access the members. To declare a protected member, use the keyword protected.
Public:
Any class, in any package ,has access to a class's public members. To declare a public member, use the keyword public.
Default :
When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.
To summarize
Object-Oriented
Fundamentally based on OOP
Uses a formal OOP type system. The object model in Java is simple and easy to understand. Efficient re-use of code. Easy to upgrade the system. Easy to maintain etc.
Robust
Java is highly reliable because
Java puts a lot of emphasis on early checking for possible problems, later dynamic (runtime) checking, and eliminating situations that are error. SecurityManager to check which operations a piece of code is allowed to do.
Secure
Designed with the intention of being secure, because the program must execute reliably in a variety of systems.
Java's robustness features help to make it more secure .
Architecture-Neutral/Portable
Write once; run anywhere, any time, forever. The Java Virtual Machine becomes the common denominator.
Bytecodes are common across all platforms. JVM hides the complexity of working on a particular platform.
Difficult to implement a JVM. But simpler for the application developer.
High-Performance
Java performance IS slower than C becuase
Interpreted languages will run slowly. Additional checks in Java which make is secure and robust and network aware etc, all have a influence on performance.
BUT
JIT compilation and HotSpot Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler. HotSpot optimizes code on the fly based on dynamic execution patterns
Can sometimes be even faster than compiled C code!
Multi-Threaded
Java supports multithreaded programming.
Java allows us to write programs that do many things simultaneously.
Processes - application level. Threads within the application.
Dynamic
Java is designed to be able to adapt to an evolving environment in at least two ways:
First, at the language level, by adding new packages of classes to its libraries; Second, at the program level, by being able to load in new classes dynamically as the program runs. load new classes at runtime.
Distributed
Java is designed for the distributed environment of the Internet.
Java has built-in classes to support various levels of network connectivity. These are found in the java.net package.
// Demonstrate lifetime of a variable, c++ program #include<stdio.h> main() { fun1(); fun1(); fun1(); } void fun1() { static int n; n++; printf( The value of n is %d \n,n); } The output of above program is The value of n is 1 The value of n is 2 The value of n is 1 Life time is until program ends . The value of the variable persists between different function calls.
// Demonstrate lifetime of a variable, c++ program public class demo { public static void main( String args[]) { fun1(); fun1(); fun1(); } static void fun1() { int x=1; x++; System.out.println(x); } } Output: 2 2 2