Java for begineers

36
Contact us SOFTORIX TECHNOLOGIES PVT LTD 72-A, 1st floor 100 feet road,Vadapalani, Chennai-600026, Tel-044 43069973,Mob-9500041042 Email:[email protected] Website: www.softorix.com

description

Java for begineers

Transcript of Java for begineers

Page 1: Java for begineers

Contact us

SOFTORIX TECHNOLOGIES PVT LTD

72-A, 1st floor 100 feet road,Vadapalani, Chennai-600026,

Tel-044 43069973,Mob-9500041042

Email:[email protected]

Website: www.softorix.com

Page 2: Java for begineers

JAVA BASICS

Page 3: Java for begineers

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

Page 4: Java for begineers

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.

Page 5: Java for begineers

Features of JAVA

Some features of Java:

– The Java Virtual Machine– Garbage Collection– Code Security

Page 6: Java for begineers

Sample JAVA programpublic 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

Page 7: Java for begineers

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

Page 8: Java for begineers

Phases of Java

• Write-tool: on any text editoro/p: file with .java extension• Compile- tool: Java Compilero/p: file with .class extension

(byte code)• Run- tool: Java Interpretero/p: program output

Java Program(.java)

Java Compiler(javac)

Byte Code(.class)

Interpreter(java) Interpreter(java) Interpreter(java)

Win32 Linux Mac

Page 9: Java for begineers

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.

Page 10: Java for begineers

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)

Page 11: Java for begineers

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 */

Page 12: Java for begineers

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;

Page 13: Java for begineers

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

}}

Page 14: Java for begineers

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

Page 15: Java for begineers

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

Page 16: Java for begineers

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

Page 17: Java for begineers

Example: Objects and Classes

BR002

CR003

DR004

AR001

classobject

Class StudentnamerollNosetName()setRollNo()getMarks()

Page 18: Java for begineers

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

Page 19: Java for begineers

Example method

public static int addNums(int num1, int num2){

int answer = num1 + num2;return answer;

}

signature

body

Page 20: Java for begineers

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’};

Page 21: Java for begineers

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;

}

Page 22: Java for begineers

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 arraysx = new int[3][4];/*Create 3 new int arrays, each having 4 elements

3 Rows and 4 Columns

Page 23: Java for begineers

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 arrayint [] x;//Create a new int array and make x refer to itx = new int[5];

Page 24: Java for begineers

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;

Page 25: Java for begineers

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

Page 26: Java for begineers

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

Page 27: Java for begineers

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 Memberspublic PolicyHolder(){

bonus = 100;}//Other Methods

}

User defined Constructor

PolicyHolder policyHolder = new PolicyHolder();//policyHolder.bonus is initialized to 100

Page 28: Java for begineers

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);}

Page 29: Java for begineers

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

Page 30: Java for begineers

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 ClassSub/Child Class

Page 31: Java for begineers

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();

Page 32: Java for begineers

Example

public class TermInsurancePolicy extends Policy{//Other Data and Methodspublic double getBenefit(){

//Code goes here}

}

public abstract class Policy{//Other Data and Methodspublic abstract double getBenefit();

}

public class EndowmentPolicy extends Policy{//Other Data and Methodspublic double getBenefit(){

//Code goes here}

}

Page 33: Java for begineers

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

Page 34: Java for begineers

Example:interface Editor{

public void edit();}//ProgramEditor is an Editorinterface 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();}

Page 35: Java for begineers

Abstract Classes Vs InterfacesAbstract Classes Interfaces

Can have concrete methods Can have only abstract methods

Can have variables Can have only static final (constant) data members

Can have private and protected members

All members are public by default

Can be extended from one class Can be extended from any number of interfaces

A class can extend only one abstract class

A class can implement any number of interfaces

Page 36: Java for begineers

THANK YOU!!!