72-A, 1st floor 100 feet road,Vadapalani, Chennai-600026, Tel-044 43069973,Mob-9500041042 Email:info@softorix.com Website: www.softorix.com JAVA BASICS Characteristics of Java Java is platform independent A Java program that is written and compiled in one platform can run on any other platform without any recompilation or modification Write Once Run Anywhere Java is a very powerful OO programming language developed by Sun Microsystems Java is widely used for developing web applications Java is the programming language used for developing Enterprise Applications using the JEE Platform
Deployment Environments There are two main deployment environments:
1. The JRE supplied by the Java 2 Software Development Kit (SDK) contains the complete set of class files for all the Java technology packages, which includes basic language classes, GUI component classes, and so on.
2. The other main deployment environment is on your web browser. Most commercial browsers supply a Java technology interpreter and runtime environment.
Features of JAVA Some features of Java:
The Java Virtual Machine Garbage Collection Code Security
Sample JAVA program public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world!"); } } The main method is public so that it can be accessed outside the class is static so that it can be invoked without creating any objects is void and does not return anything can take command line arguments as an array of String
Using a string: public class hello{ public static void main (String [] args) { String s = Hello World\n; System.out.println(s); //output simple string// } //end main }//end class hello
Phases of Java Write- tool: on any text editor o/p: file with .java extension Compile- tool: Java Compiler o/p: file with .class extension (byte code) Run- tool: Java Interpreter o/p: program output
Java Program(.java) Java Compiler(javac) Byte Code(.class) Interpreter(java) Interpreter(java) Interpreter(java) Win32 Linux Mac Difference between C and Java C uses concept of structures (not object oriented). In C we use the concept of pointers In C the programmer needs to manage memory manually. "malloc()" and "free()" are the fundamental memory allocation library calls but JAVA has automatic garbage collector and memory management. In C the declaration of variables should be on the beginning of the block but JAVA variables can be declared wherever we want to.
Primitive Types Integer Types byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes) Floating Type float (4 bytes) double (8 bytes Textual char (2 bytes) Logical boolean (1 byte) (true/false)
Comments in Java A single line comment in Java will start with //
A multi line comment starts with a /* and ends with a */
// This is a single line comment in Java /* This is a multi line comment in Java */ Variables Declaring and using primitive data types is Java similar to that of C
Unlike C, in Java variables can be declared anywhere in the program
int i = 10; System.out.println(Program starts here); int j = 20; for (int count=0; count < max; count++) { int z = count * 10; } BEST PRACTICE: Declare a variable in program only when required. int count; int max=100; Local Variables In Java, if a local variable is used without initializing it, the compiler will show an error
class Sample{ public static void main (String [] args){ int count; System.out.println(count);//Error } } Typecasting of primitive data types Variable of smaller capacity can be assigned to another variable of bigger capacity without any explicit typecasting
Whenever a larger type is converted to a smaller type, the typecast operator has to be explicitly specified
int i = 10; double d; d = i; double d = 10; int i; i = (int) d; Type cast operator Operators and Control Statements Operators in Java are very similar to operators in C Assignment Operators Arithmetic Operators Relational Operators Logical Operators The syntax of the control statements in Java are very similar to that of C language if if-else for while do-while switch break continue
What is a Class? A Class Is a blue print used to create objects. Is a software template that defines the methods and variables to be included in a particular kind of Object. Examples Animal, Human Being, Automobiles, Bank Account, Customer A class contains state and behavior State (Member Variables) Variables defined inside the class Not exposed to external world Behavior (Member Methods) Functions defined inside the class Behavior exhibited by the class to external world Exposed to external world An object is an instance of a class
Example: Objects and Classes B R002 C R003 D R004 A R001 class object Class Student name rollNo setName() setRollNo() getMarks() Methods in Java
The syntax of writing methods in Java is similar to that of functions in C Unlike C All methods in Java should be written inside a class There is no default return type for a Java method
Example method
public static int addNums(int num1, int num2) { int answer = num1 + num2; return answer; }
signature body Arrays in Java In Java, all arrays are created dynamically using the keyword new. The operator new is used for dynamic memory allocation The following statement creates an array of 5 integers
The above statement returns a reference to the newly created array References in Java are very similar to pointers in C An array can be initialized while it is created as follows new int[5] int [] x = {1, 2, 3, 4}; char [] c = {a, b, c}; Length of an Array Unlike C, Java checks the boundary of an array while accessing an element in it Java will not allow the programmer to exceed its boundary If x is a reference to an array, x.length will give you the length of the array The for loops can be set up as follows for(int i = 0; i < x.length; ++i){ x[i] = 5; } Multidimensional Arrays
Multidimensional arrays are arrays of arrays. To declare a multidimensional array variable, specify each additional index using another set of square brackets.
int [][] x; //x is a reference to an array of int arrays x = new int[3][4]; /*Create 3 new int arrays, each having 4 elements
3 Rows and 4 Columns Reference variables in Java
Reference variables are used in Java to store the references of the objects created by the operator new Any one of the following syntax can be used to create a reference to an int array
The reference x can be used for referring to any int array
int x[]; int [] x; //Declare a reference to an int array int [] x; //Create a new int array and make x refer to it x = new int[5]; Cont. The following statement also creates a new int array and assigns its reference to x
In simple terms, reference can be seen as the name of the array A reference type can be assigned null to show that it is not referring to any object null is a keyword in Java
int [] x = new int[5]; int [] x = null; Cont. Pointers References Printing a pointer will print the address stored in it
Printing a reference will NOT print the address of the object referred by it
Pointer arithmetic like incrementing a pointer is valid in the case of a pointer
We cannot use arithmetic operators on references
A pointer has to be de-referenced using the * operator to get the value pointed by it
A reference is automatically de- referenced to give the data referred by it and no special operator is required for this
Even though we can think of Java references as C pointers, their usages are different
Constructors A constructor is a special method that is called to create a new object
It is not mandatory for the coder to write a constructor for the class It can be seen as a readily available, implicit method in every class The constructor initializes the data members of an object to some default values. Note that local variables of a method are not initialized automatically and using a variable that is not initialized will result in a compilation error in the program.
PolicyHolder policyHolder = new PolicyHolder(); Calling the constructor Cont. A constructor method will have the same name as that of the class will not have any return type, not even void
public class PolicyHolder{ //Data Members public PolicyHolder(){ bonus = 100; } //Other Methods } User defined Constructor PolicyHolder policyHolder = new PolicyHolder(); //policyHolder.bonus is initialized to 100 Method Overloading Two or more methods in a Java class can have the same name, if their argument lists are different Argument list could differ in No of parameters Data type of parameters Sequence of parameters This feature is known as Method Overloading
void print(int i){ System.out.println(i); } void print(double d){ System.out.println(d); } void print(char c){ System.out.println(c); } Cont. 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)
void add (int a, float b) int add (int a, float b) Overloaded Methods Not Overloaded Methods Just like other methods, constructors also can be overloaded The constructor without any parameter is called a default constructor Inheritance When the programmer wants to create a new class that needs all the properties of an existing class with some more extra features, the new class need not be programmed from the scratch. Instead the new class can be inherited from the old class using the keyword extends. The programmer needs to add only the additional features needed by the new class. Inheritance leads to code re-usability.
The keyword extends is used in Java to inherit a sub class from a super class
public class TermInsurancePolicy extends Policy{ //Data Members and Methods } Super Class Sub/Child Class Abstract Class A method without a body is known as an abstract method and qualified by the keyword abstract
A class that has at least one abstract method is known as an abstract class and should be qualified using the keyword abstract Abstract classes cannot be instantiated They are used as base classes for other classes Subclasses that extend an abstract class need to provide implementation of all the abstract methods of the base class or declare the subclass also as abstract The following cannot be abstract Constructors Static methods Private methods
public abstract double getBenefit(); Example public class TermInsurancePolicy extends Policy{ //Other Data and Methods public double getBenefit(){ //Code goes here } } public abstract class Policy{ //Other Data and Methods public abstract double getBenefit(); } public class EndowmentPolicy extends Policy{ //Other Data and Methods public double getBenefit(){ //Code goes here } } Interface Multiple Inheritances is not permitted in JAVA so comes a concept called INTERFACE that is a class can extend one class and implement an interface at the same time An interface cannot have concrete methods in it nor can it have member variables A data members declared in an interface are implicitly public, final and static and hence become constants
Example: interface Editor{ public void edit(); } //ProgramEditor is an Editor interface ProgramEditor extends Editor{ public void highlightKeywords(); } Unlike classes, an interface can be extended from more than one interface
interface Editor{ public void edit(); } interface Painter{ public void draw(); } interface EditorWithPainter extends Editor, Painter{ public void wrapTextAroundPicture(); } Abstract Classes Vs Interfaces Abstract Classes
Interfaces
Can have concrete methods
Can have only abstract methods
Can have variables
Can have only static final (constant) data members