181 Learning Java

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View 181 Learning Java as PDF for free.

More details

  • Words: 4,416
  • Pages: 51
COMPUTER APPLICATIONS Tutorial on JAVA

Dheeraj Mehrotra City Montessori School & Degree College Lucknow (India) [email protected] www.computerscienceexpertise.com Towards QUALITY IT LITERACY FOR ALL

PDF created with pdfFactory Pro trial version www.pdffactory.com

Concept of OOP o OOP stands for Object Oriented Programming. It is the latest trend in programming languages supported by C++ and Java and has had the revolutionary success in the race of OOP. The limitations of the Procedure Oriented Programming (POP) languages, have given place to the development of the OOP.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

CLASSES & OBJECTS o

Object :

o

An object is an identifiable entity with some characteristic and behaviour.

o

Class :

o

A Class is a group of objects that share common properties and relationships.

o

The Objects are variables of type Class eg.

o

If animal has been defined as a Class, then the statement;

o

animal dog;

o

will create an Object featuring dog belonging to the class animal.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

CORE CONCEPTS OF OOP o The basic concepts of Object Oriented Programming (OOP) are : n n n n

Abstraction Encapsulation Inheritance Polymorphism

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Features of OOP o

Abstraction refers to the act of representing essential features without including the background details or explanations.

o

Encapsulation is an act of wrapping up of data and methods into a single unit (called class). It is one of the most fundamental concepts of the Object Oriented programming. The very insulation of the data from direct access by the program is termed as Data Hiding. Encapsulation, is hence, just a way to implement Abstraction.

o

Inheritance is the process by which objects of one class acquire the properties of objects of another class. This further provides an important extension to the idea of reusability. i.e. a particular programmer can make use of an existing class and without any further modifications, add additional features and capabilities to it, by deriving a new class from the existing one, through inheritance.

o

Polymorphism is the capacity to allow objects having different internal structures to share the same external interface. It is the ability for a message or data to be processed in more than one form.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

ADVANTAGES OF OOP o Elimination of redundant coding system and usage of existing classes through inheritence. o Programs can be developed by sharing existing modules. o Security of data values from other segments of the program through data hiding. o Possibility of co-existence of multiple instances of an object without any interference.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Few Examples of OOP Languages o The different Object Oriented Programming Languages are C++, Java, Smalltalk, Simula, Eiffel etc.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

History of JAVA o JAVA is an object oriented programming language. It was developed by Sun Microsystems in 1991 as a part of the research work to develop software for consumer electronics. It was designed to be small, simple and portable across platforms and operating systems, both at the source and at the binary level. It was developed as a full-fledged programming language in which one can accomplish the same sorts of tasks and solve the similar problems that one can in other programming languages, such as C++, BASIC etc.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

About JAVA o Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Why JAVA o The Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devicestelevision sets, VCRs, toasters, and the other sorts of machines you can buy at any department store. Java's goals at that time were to be small, fast, efficient, and easily portable to a wide range of hardware devices. It is those same goals that made Java an ideal language for distributing executable programs via the World Wide Web, and also a general-purpose programming language for developing programs that are easily usable and portable across different platforms. This is the major reason why Java is said to be the most successful platform independent language.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Advantages of Java o Java as a language has significant advantages over other languages and other programming environments that make it suitable for just about any programming task. Some of them are listed as follows:

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

o Applets Applets appear in a Web page much in the same way as images do, but unlike images, applets are dynamic and interactive. Applets can be used to create animations, figures, or areas that can respond to input from the reader, games, or other interactive effects on the same Web pages among the text and graphics. Java enabled browsers can successfully run applets and thus give a truly rich experience at the user end. [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

o

Platform Independence Platform independence is one of the most significant advantages that Java has over other programming languages, particularly for systems that need to work on many different platforms. Java is platform-independent at both the source and the binary level. Platformindependence is a program's capability of moving easily from one computer system to another. Java binary files called byte-codes are also platform-independent and can run on multiple platforms without the need to recompile the source. Byte-codes are a set of instructions that look a lot like machine code, but are not specific to any one processor. Because of them, compilation happens just once; interpretation occurs each time the program is executed. Java byte-codes help make "write once, run anywhere" possible.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

o Simplicity In addition to its portability and objectorientation, one of Java's initial design goals was to be small and simple, and therefore easier to write, easier to compile, easier to debug, and, best of all, easy to learn. Keeping the language small also makes it more robust because there are fewer chances for programmers to make difficult-to-find mistakes. Despite its size and simple design, however, Java still has a great deal of power and flexibility. [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

o

Better Cousin of C, C++ Java is modeled after C and C++, and much of the syntax and object-oriented structure is borrowed from the latter. If you are familiar with C++, learning Java will be particularly easy for you, because you have most of the foundation already. Although Java looks similar to C and C++, most of the more complex parts of those languages have been excluded from Java, making the language simpler without sacrificing much of its power. There are no pointers in Java, nor is there pointer arithmetic. Strings and arrays are real objects in Java. Memory management is automatic. To an experienced programmer, these omissions may be difficult to get used to, but to beginners or programmers who have worked in other languages; they make the Java language far easier to learn.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

o

o

Applets and Applications The most common types of programs written in the Java programming language are applets and applications. If you've surfed the Web, you're probably already familiar with applets. An applet is a program that adheres to certain conventions that allow it to run within a Java-enabled browser. An application is a standalone program that runs directly on the Java platform. A special kind of application known as a server serves and supports clients on a network. Examples of servers are Web servers, proxy servers, mail servers, and print servers. Another specialized program is a servlet. A servlet can almost be thought of as an applet that runs on the server side. Java Servlets are a popular choice for building interactive web applications, replacing the use of CGI scripts. Servlets are similar to applets in that they are runtime extensions of applications. Instead of working in browsers, though, servlets run within Java Web servers, configuring or tailoring the server.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Dual Utility of JAVA o

The programs developed in Java fall into two main categories : applications and applets.

o

The Java Applications are general programs like any other programming language. They can perform any required operation/task or application.

o

The Java Applets are Java Programs that are downloaded over the World Wide Web and are executed as a part of Web page, by a Web Browser on the machine. The Applets can create games, interactive programs, animations and develop multimedia effects on the web page.

o

A program written in JAVA can be either an application or an applet or both, depending on the writing structure of the program. [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Character set of JAVA o Letters A-Z and a-z, 0-9 digits, special symbols like Space, +, -, *, /, ^, \, (, ), {, }, [, ], =, !=, <, >, ., ‘, “, $, ;, :, %, !, &, ?, -, #, @, <=, >= and white spaces like blank space, horizontal tab, carriage return, newline, form feed etc.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Tokens of JAVA o JAVA comprises of tokens as smallest element of the program. They implement various features within a program. They are as follows : o o o o o

Keywords Identifiers Literals Separators Operators

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

STRUCTURE OF A JAVA PROGRAM o The program written in Java has two main parts : n Enclosure of the program in a class definition. n Enclosure of the body of the program in the functions.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Example Program in JAVA class exampleprogram { public static void main(string args[ ]) { System.out.println(“Hail The World !”); } }

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

In the above program, the first line class exampleprogram

class exampleprogram {public static void main(string args[ ]) {System.out.println(“Hail The World !”);}}

declares a class named exampleprogram, where class is the reserve word. Exampleprogram is an identifier as supplied by the programmer.

This is followed by brace {, which indicates the beginning of the block of executable statements. The third line : public static void main(string args[ ]) defines the function main( ). The declaration of the main() function contains the following keywords: Public, Static and Void. The Public keyword acts as an access specifier which declares the main function to be publically accessible for other classes. The Static definition declares that the very function or method is independent of the entire class and does not figure as a part of any objects of the class. In the above program, the class exampleprogram is unchanging or static, as a state. The term static means unchanging and implicitly final. The Void is a data type modifier which defines the main() function of no return type. The argument of the main() function lies within braces eg. (String args[ ]), here String args[ ] declares an argument parameter [email protected] args containing an array of objects of the class type String. It specifies that the main method takes an argument that is an object of string. PDF created with pdfFactory Pro trial version www.pdffactory.com

BlueJ Environment? To make effective use of BlueJ, one has to eliminate the very un-object-oriented public static void main and replace it with other function name so as to instantiate the object and call the method for execution.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Programming Instructions In JAVA Output Statements: The println( ) method or the function is used to display information on the screen. It also provides a line feed i.e. transfers the control to the next line of the output. // Example program to utilize println( ) method class output { public void display() {int a=10; int b=20; int c=30; int d=40; System.out.println("The System.out.println("The System.out.println("The System.out.println("The System.out.println("The }}

usage of println( ) method"); value of a is "+a); value of b is "+b); value of c is "+c); value of d is "+d); [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Remark Statement of JAVA The Java language offers provision of remark within its program in the following three ways : (i). Using /* and */ eg. /* This program prints the sum of two numbers */ (ii). Using // for a single line of comment. eg. // This program prints the sum of two numbers (iii). Using /** and */ eg. /** This program prints the sum of two numbers */

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Data Types (int) Type

Size

Min. Range

byte

One Byte

-128

short

Two Bytes

-32,768

int

Four Bytes 2,147,483,647

Max.Range

-2,147,483,648

127 32,767 To

long Eight Bytes -9,223,372,036,854,775,808 To 9,223,372,036,854,775,807

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Data Types (float) This type of data includes numbers with decimal part or fractional numbers. It is further classified into two types as float and double with references as : Type

Size

Min. Range

Max. Range

float

4

3.4e-038 to

3.4e+038

double

8

1.7e-308 to

1.7e+308

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Escape Sequences in JAVA Escape \n \t \b \r \f \\ \’ \” \ddd \xdd \udddd

Meaning Newline Tab Backspace Carriage return Formfeed Backslash Single Code Double Code Octal Hexadecimal Unicode Character

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Declaration of Variables in JAVA A Declaration of a variable refers to the following: (i). Specification of the name of the variable. (ii). Specification of the data type of the variable. (iii). Specification of the scope of usage of the variable. eg. int age; String name; boolean isAbsent; [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Arithmetic Operators Operator + * / %

Meaning Addition Substraction Product Division Modulus

Format a+b a-b a*b a/b a%b

where a and b are the two numeric constants.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Assignment Operators Operator/ Operation/ Format/ Meaning =

Assignment

a=10

10 assigned to the variable a

+=

Add to the variable

a+=5

a=a+5

-=

Subtract from variable

a-=5

a=a-5

*=

Multiply to variable

a*=5

a=a*5

/=

Divide into

a/=5

a=a/5

%=

Modulus of

a%=5

a=a%5

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Shorthand Notation Shorthand Operation

Equivalence Operation

sum sum sum sum sum

sum sum sum sum sum

+=10; -=10; /=10; *=10; %=10;

= = = = =

sum sum sum sum sum

+ 10; - 10; / 10; * 10; % 10;

(Similarly a variable within an expression on the right can also be used as :) sum +=total;

sum = sum + total;

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Increment & Decrement Operators The increment operator is indicated by ++ and is used to increment the variable by 1. eg. ++marks; increments the value of the variable marks by 1. It can be used in two ways : as a prefix, (++var), meaning that the operator precedes the variable; and as a postfix, (var++), where the operator follows the variable. In prefix the variable gets incremented first where as in postfix the variable gets incremented after the operation of function of its associate operator. Decrement Operators are similar to Increment Operators except the fact for the operation of decrementation by 1. It can also be used both as prefix and postfix forms of its format. eg. --marks; is used to decrement the value of marks by 1. [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Ternary Operator of JAVA This is an excellent substitute to the control statement like IF/THEN/ELSE of BASIC language. It is denoted by the combinational characters ?: and follows the usage with the following format/syntax : value variable = (test expression) ? expression1 : expression2; which indicates that if the test expression is true then the transfer value for storage into the value variable is expression1 and if the test expression is false the transfer value becomes the expression2. for example: grade = (total > 40) ? ‘P’ : ‘F’; In the above example grade refers to the value variable, total>40 is the test expression, ‘P’ is the expression1 and ‘F’ is the expression2. The ? character follows the true condition and : follows the false condition. [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Control Statements of JAVA Selection control statements : The Selection control statements refer to transfer of control or execution depending on the given condition and a selection is made depending on the given options. The different course of action are performed according to the given condition. They are also termed as Decision Construct Statements as they help in taking decisions for further execution of the statements/instructions within the program. Iteration control statements : The Iteration Statements on the other hand act as an automatic looping statements. Here the block/compound statement is executed again and again until a given condition is met.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

IF Statement

This statement acts as a conditional control statement of Java and checks the specified condition. If the given condition is true the given instruction is executed otherwise the instruction is ignored. There are different formats of if statement and is widely used for computation, logical reasoning and decision making within a program. A simple if statement has the following format : if (expression) statement1; where an expression is the condition which if found true executes statement1 otherwise the control comes to the next statement.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

IF – ELSE Statement This conditional control statement of Java conducts the execution of the statement if the condition is true and conducts other specified execution if the condition is false. It consists of an if statement, followed by a statement or block of statements, followed by the keyword else, followed by another statement or block of statements. It has the following syntax : if (expression) statement 1; else statement 2; If the expression is true, the statement 1 is executed otherwise the statement 2 is executed. The statement 1 and statement 2 can be a single statement or a block/compound statements. [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Switch Statement It has the following format : switch(expression) { case value1: block1 break; case value2: block2 break; ———default: block break; }The break statement used at the end of each case acts as an exit point from the

switch statement. It works as a jumping statement and the execution is transferred to the statement following the switch statement. The Default statement is the executing condition in the condition when the value of switch does not match with the case. It does not require any usage of break as it is always the last segment of the switch structure. [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Difference Between SWITCH / IF-ELSE i). The IF-ELSE statement is used for manipulating multiple conditions whereas SWITCH touches upon only one conditional variable. And different values of the variable passes the control to the required case. (ii). The IF-ELSE statement uses both integer as well as floating type values whereas the SWITCH statement only accepts integer values. (iii). In SWITCH statement all the branches or compound statements are executed depending on the value of the same variable on the other hand IF-ELSE follows usage of long instruction based statements and may create confusion within blocks.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

While Statement of JAVA The while statement is another looping statement of Java with an entry control option for execution. It acts as one of the simplest looping structures of Java and has the following format. Initialization; while (test expression) { body of the loop } where the test expression is the conditional state which executes the body of the loop if it returns the true value and terminates once the value returned for the test condition is false. It acts as an entry controlled loop and the given test expression is evaluated at every execution of the body of the loop. [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Do While Statement of JAVA This format of the WHILE statement is an exit controlled iteration statement. In this the condition which is to be checked lies at the end of the execution statement/statements and is hence executed at least once no matter the conditon is met or not. It has the following format : do {

body of the loop

} while (test expression);

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

FOR LOOP IN JAVA This acts as an automatic looping statement with all the control elements/conditions placed in one place. It is equivalent to the FOR/NEXT of BASIC high-level language. It has the following format : for (initialization expression;testexpression;update expression) { loop body } It starts with the keyword for, followed by parentheses that contains three expressions separated by semicolons. eg.for (s=1;j<11;j++) The above segment assigns the loop variable s by 1, the test condition is j<11 and the increment expression is j++. The loop executes for 10 times, with the value of s ranging from 1 to 10.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

VISIBILITY LABELS/ ACCESS MODIFIERS The visibility labels are of two major types viz. public and private. The method or a variable with modifier public is accessible wherever the program has access to an object. Any instance variable or method declared with class private is accessible only to methods of the class.The instance variable private are accessible to methods of the class. The instance variables are normally declared private and the methods are declared as public.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

CONSTRUCTORS A class is a combination of member variables and methods. The member variables are initialized by a constructor. All Java classes have special methods called constructors that are used to initialize a new object of that type. A constructor is a method with the same name as a class. It is invoked automatically each time an object of that class is initiated. It does not return any value. Java supports method name overloading, so that a class can have any number of constructors, all of which have the same name. Like other overloaded methods, constructors are differentiated from one another by the number or type of their arguments.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

CONSTRUCTOR TYPES a. Overloaded Constructors: Under this format the constructor methods are utilized to initialize the object using the parameter argument. The arguments are passed to the constructors and appropriate constructor is invoked by matching the number, types and order of the arguments specified in each method definition. b. Default Constructors: The default constructors are used to initialize all the variables to a 0 value. As per the procedure in Java all variables must be initialized when the object is initialized. This is compulsory and it is done by use of a constructor.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

STRING Manipulation JAVA offers string manipulation using the functions. In order to declare a string variable the following format is used : Declaration of a String in JAVA: String var-name; var-name = new String(“value”);

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

String Functions in JAVA i). toLowerCase;

FORMAT: a2=a1.toLowerCase; USAGE: This function/method converts all the characters of the string in lowercase. (ii). toUpperCase; FORMAT: a2=a1.toUpperCase; USAGE: This function/method is used to convert all the characters of the string a1 into uppercase. (iii). replace(); FORMAT: a2 = a1.replace(‘n’,’m’); USAGE: This function replaces all the occurances of the character ‘n’ with ‘m’ in the string a1. (iv). trim(); FORMAT: a2=a1.trim(); USAGE: This function is used to remove all the white spaces at the beginning and end of the string a1.

(v). equals(); FORMAT: a1.equals(a2); USAGE: This method gives ‘true’ if a1 string is equal to a2. (vi). length(); FORMAT: a1.length(); USAGE: This function returns the length of characters present in the string. (vii). ChartAt(); FORMAT: a1.ChartAt(n); USAGE: This function/method returns nth character of the string a1. (viii). concat(); FORMAT: a1.concat(a2); USAGE: This function concatenates a1 and a2 strings. (ix). substring() FORMAT: a1.substring(n); USAGE: This returns substring starting from the nth character of the string a1.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

String Functions (Cont.) (xi). indexOf(); FORMAT: a1.indexOf(‘d’); USAGE: This returns the position of the first occurrence of ‘d’ in the string a1. (xii). indexOf(); [another format] FORMAT: a1.indexOf(‘d’,n); USAGE: This format gives the position of ‘d’ starting from the nth position in the string variable a1. (xiii). compareTo() FORMAT: a1.compareTo(a2); USAGE: This function returns negative if a1 is less than a2, positive if a1 is greater than a2 and zero if a1 is equal to a2.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Program Using String Functions // Program to input a string and print the length of the string // In uppercase, in lowercase and in reverse. class stringisc { public static void inputstring(String name) { System.out.println("The entered string is "+name); int len,words=0; len=name.length(); System.out.println("The length of the string entered is "+len); System.out.println("The string in reverse is "); for(int i=len-1;i>=0;i--) System.out.print(name.charAt(i)); // Printing the string in lower case System.out.println("The name in lowercase is "); System.out.print(name.toLowerCase()); System.out.println("The name in uppercase is "); System.out.print(name.toUpperCase()); } } [email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Math Functions of JAVA (i). sin():

(vi). atan();

FORMAT: Math.sin(a);

FORMAT: Math.atan(a);

(ii). cos();

(vii). pow();

(x). floor()

FORMAT: Math.cos(a);

FORMAT: Math.pow(a,b);

FORMAT: Math.floor(a);

(iii). tan();

(viii). exp()

FORMAT: Math.tan(a);

FORMAT: Math.exp(a);

(iv). asin();

(ix). log()

FORMAT: Math.abs(a);

FORMAT: Math.asin(a);

FORMAT: Math.log(a);

(xiii). max()

(v). acos();

(x). sqrt()

FORMAT: Math.acos();

FORMAT: Math.sqrt(a);

(xi). ceil() FORMAT: Math.ceil(a);

(xi). rint() FORMAT: Math.rint(a); (xii). abs()

FORMAT: Math.max(a,b); (xiv). min() FORMAT: Math.min(a,b);

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

o End of Session.

n Thank you §

Send your queries at

§

[email protected]

§

Visit: www.computerscienceexpertise.com

§

Towards Quality IT Literacy for All.

[email protected]

PDF created with pdfFactory Pro trial version www.pdffactory.com

Related Documents

181 Learning Java
November 2019 1
Learning Java
May 2020 1
181
November 2019 30
181
July 2020 36
181
May 2020 20
181
November 2019 21