53511158-39336505-Java-Info - JAVA JAVA INTRODUCTION Java...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: JAVA JAVA INTRODUCTION Java is a programming language developed at SUN MICROSYSTEMS. The language derives much of its syntax from c and c++ but has a simpler object model. Java applications are typically compiled to byte code that can run on any JAVA VIRTUAL MACHINE regardless of computer architecture. Java is a general­ purpose, class­based, object­oriented programming language. It is intended to let application developers “WRITE ONCE, RUN ANYWHERE”. Java is currently one of the most popular programming language in use and is widely used from application software to web applications. CHARACTERISTICS OF JAVA CHARACTERISTICS SIMPLE – java was designed to be easy for the programmer to learn and use effectively. OBJECT ORIENTED – java is an object oriented language. All java programs to some extent are object oriented. ROBUST – Java checks our code at compile time as well as run time. MULTITHREADED – it allows to write programs that do many things simultaneously. CONTD… DYNAMIC – Java programs carry with them substantial amount of information which makes it possible to dynamically link code in a safe manner. SECURITY– the code which is being downloaded may contain virus, Trojan horse or other harmful code. Java achieved protection from these by confining an applet to the java execution environment. PORTABILITY – it means that the same code must work on all computers. DISTRIBUTED – java is designed for the distributed environment of the internet because it handles TCP/IP protocols. OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING Object oriented programming is at the core of java. All java programs to some extent are object oriented. It organizes a program around its data and a set of well defined interfaces to that data. OOP PRINCIPLES­ Abstraction Encapsulation Inheritance polymorphism CONTD… ABSTRACTION Abstraction is defined as the sharing of only the essential and important data. It is an important element of object­oriented programming. ENCAPSULATION It is the mechanism that binds together code and the data it manipulates and keeps both safe from outside interference and misuse. INHERITANCE It is the process by which one object acquires the properties of another object. There are many types of inheritance like single, multiple, multilevel and hybrid. POLYMORPHISM It means “many forms”. It is the feature that allows one interface to be used for a general class of actions. JAVA APPLETS An applet is a special kind of java program that is designed to be transmitted over the internet and automatically executed by a java compatible web browser. It is typically used to display data provided by the server and handle user input. The applet is a dynamic, self­ executing program. THE BYTECODE The bytecode is a highly optimized set of instructions designed to be executed by the java runtime system which is called the JAVA VIRTUAL MACHINE(JVM). The JVM was designed as an interpreter for bytecode. SERVLETS A servlet is a small program that executes on the server. Servlets dynamically extend the functionality of a web server. Servlets are highly portable as they are compiled into bytecode and executed by the JVM. SIMPLE JAVA PROGRAM SIMPLE JAVA PROGRAM class HelloWorld { { } } public static void main (String args) System.out.println("Hello World!"); This is a simple hello world application as written in java. We have to save it as a file name helloworld.java. This program will display the message Hello World!. To compile the java code we need to use the ‘javac’ tool. The command line to compile this program is – javac HelloWorld.java JAVA COMMENTS JAVA COMMENTS The java programming language supports three types of comments­ 1. /*text*/­ The compiler ignores everything from /* to */. 2. /**documentation*/­ This indicates a documentation comment. The compiler ignores this kind of comment also. 3. //text­ The compiler ignores everything from // to the end of the line. JAVA DATATYPES There are 8 primitive data types. These data types are numeric type. These are – Char(2 bytes, unsigned, Unicode, 0 to 65,535 ) Boolean(1 bit­true or false) and Floating Point Primitive Data Types Integer Primitive Data Types Size Range float 32 bits ­3.4E+38 to +3.4E+38 double 64 bits ­1.7E+308 to 1.7E+308 Type Size Range byte Type 8 bits ­128 to +127 short 16 bits ­32,768 to +32,767 int 32 bits (about)­2 billion to +2 billion long 64 bits (about)­10E18 to +10E18 OPERATORS OPERATORS An operator is a symbol that operates on certain data type. Arithmetic operators(+, ­, *, /, %) Relational operators(<, >, ==, !=, <=, >=) Logical operators(&&, ||, !) Assignment operators (=) Increment / decrement operators (++, ­­) Conditional operators ( ? :) Bitwise operators (&, |, ^, <<, >>, ~) Others (new, delete, typedef, sizeof, etc) ARITHMETIC EXPRESSIONS ARITHMETIC EXPRESSIONS An expression consists of a syntactically valid combination of operators and operands that computes to a value An expression, which has a value, by itself is not a statement as it does not terminate with semicolon. 3 * 4 / 2 is an expression with value 2. X = 3 * 4 is an example of an assignment expression (no semicolon) and has a value equal to RHS of the assignment operator. Thus z = ( x = 3 * 4) / 5 ; is valid and z is assigned a value 2. Similarly z = y = x = 3; is also valid. The rule is that assignment operators groups from right to left. ABBREVIATED ASSIGNMENT EXPRESSION ABBREVIATED ASSIGNMENT EXPRESSION n=n+5 Written as n+=5 n=n-5 Written as n-=5 n=n*5 Written as n*=5 n=n/5 Written as n/=5 n=n%5 Written as n%=5 RELATIONAL AND LOGICAL OPERATORS Op. < <= > >= == != && || != Function Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to Logical AND Logical OR Logical not Use Expr < expr Expr<= expr Expr > expr Expr >=expr Expr==expr Expr!=expr Expr && expr Expr || expr Expe != expr INCREMENTAL/DECREMENTAL OPERATOR INCREMENTAL/DECREMENTAL OPERATOR ++ increase the value by 1, hence called incremental operator ­­ decrease the value by 1, hence called decremental operator. Suppose a has a value 5 then ++a (pre­form) or a++ (post form) will assign a value of 6 to a. The difference comes in the value used for the operand a when it appears inside an expression. In pre­form, value of operand is incremented / decremented first and then the value is fetched for computing the expression. In post form, first the value of the operand is fetched, expression is computed and then the value is incremented / decremented. CONDITIONAL OPERATOR CONDITIONAL OPERATOR It has the following syntactic form: expr1 ? expr2 : expr3 ; expr1 is always evaluated to true or false. If it is true, expr2 is evaluated; otherwise expr3 is evaluated. For example int min(int a, int b) {return ( a < b) ? a ; b;} will return minimum of a and b. THE IF AND ELSE­IF STATEMENT THE IF AND ELSE­IF STATEMENT if (condition) if (condition) statement-1 { statement-1 } else statement-2 Condition can either be an expression (a+b > c) or an initialized declaration statement int ival=10; THE SWITCH STATEMENT 1.switch keyword is followed by an expression in parenthesis that is evaluated to integer value. 2. A set of case labels consisting of the keyword case followed by a constant expression of integer type followed by colon. No two case label can have the same value. 3.A sequence of program statements associated with case one or a set of case labels 4.An optional default label THE BREAK STATEMENT THE BREAK STATEMENT 1. A break statement can legally appear only some where within a loop or switch statement 2. The break statement terminates the loop THE CONTINUE STATEMENT Unlike break, which terminates the loop, continue statement terminates only the current iteration. THE FOR LOOP THE FOR LOOP for (init­statement; condition ; expression) { body of the loop } 1. Init­statement is executed once at the start of the loop. 2. Condition is executed. If it is evaluated to true, body of the loop is executed, else loop is terminated. 3. Condition is rechecked at the completion of the execution of the body of the loop. THE WHILE LOOP THE WHILE LOOP while (condition) { body of the loop } 1. Evaluate the condition 2. Execute the body­of­loop if the condition is true else terminates the loop THE DO­WHILE LOOP do {body­of­loop } while (condition); METHODS METHODS A method is a group of instructions that is given a name and can be called up at any point in a program using that name. System.out.println() is a method which requires quite a lot of code, but it is all stored in the System libraries. Methods begin with a declaration. First is an optional access specifier which can be public, private or protected. Methods are protected by default By default methods are not static. We finally specify the return type. Next is the name of the method. RECURSIVE METHODS RECURSIVE METHODS Recursion is used when a problem can be reduced into one or several problems of the same nature and smaller size until a boundary situation is reached, where the problem can be directly solved. Java supports recursive methods, i.e. methodA() can call methodA(). public static long factorial (int n) { if (n < 0) { return ­1; } else if (n == 0) { return 1; } else { return n*factorial(n­1); } } ARRAYS ARRAYS Arrays are generally effective means of storing groups of variables having same data types. An array is a group of variables that share the same name and are ordered sequentially from zero to one less than the number of variables in the array. The number of variables that can be stored in an array is called the array's dimension. Each variable in the array is called an element of the array. STEPS FOR CREATING ARRAYS STEPS FOR CREATING ARRAYS There are three steps: Declaring Arrays we suffix the type with to indicate that this variable is an array. For example:­ int[ ] k; Allocating Arrays k = new int[2]; The numbers in the brackets specify the dimension of the array Initializing Arrays k[0] = 2; k[1] = 5; The numbers used to identify them are called indexes into the array beginning with 0. TWO DIMENSIONAL ARRAYS TWO DIMENSIONAL ARRAYS class FillArray { public static void main (String args) { int M; M = new int[4][5]; for (int row=0; row < 4; row++){ for (int col=0; col < 5; col++){ M[row][col] = row+col; }}}} Here we are Using For loops to initialize the array. Declaring, allocating and initializing an array at the same time:­ float kt = {0.0f, 1.2f, 3.4f, ­9.87f, 65.4f, 0.0f}; Shortcut to create an array:­ int[ ] k = new int[3]; CLASSES CLASSES The class is the fundamental unit of Java programs. An object is a specific instance of a class. A class can have public or default (no modifier) visibility. It can be either abstract, final or concrete (no modifier). It may optionally extend one parent class. By default, it will extend java.lang.Object. The source file name is same as the public class name and it must have a .java suffix. Each .java source file may contain only one public class. Class Syntax [ public ] [ ( abstract | final ) ] class ClassName [extends Parent Class ] [ implements Interfaces ] { // variables and methods are declared here } OBJECTS OBJECTS For example; We need to keep a database of web sites. Each site have a name and a URL. class website { String name; String url; } These variables (name and url ) are called the members of the class. To instantiate an object in Java we use the new operator. To access the member variables of the website we can use the “.”(dot) operator. For example: website x = new website(); x.name = “Google"; x.url = "http://www.google.co.in"; System.out.println( “Website” + x.name + " at " + x.url); INTERFACES INTERFACES An Interface is neither a class nor a member of a class.An interface defines methods that a class implements. A class may implement one or more interfaces. The methods of an interface are abstract ­­ they have no bodies. Generally, a class implementing an interface will not only match the method specifications of the interface, it will also provide bodies implementations for its methods.For example, interface Counting { abstract void increment(); abstract int getValue(); } A class that implements a particular interface must declare this explicitly: class ScoreCounter implements Counting { .... } PACKAGES PACKAGES 1. 2. 3. 4. Packages are a collection of classes, interfaces which can be used in Java program. These are first non comment statements in java which specify the name of package where class file is to be placed Rules For Packages:­ All the components present in the package can access each other. All the public components in the package are accessible from outside the package. The protected components are accessible outside the package only if they are subclasses of protected components. Java provides no mechanism through which class can be hidden inside a package. PACKAGES PACKAGES Naming of packages:­ Name of Developer. package name. class name. method name For example:­ Java.lang.system.exit(0) Java supports two types of packages:­ 1.)Java API(System packages) Eg:­ java.lang, java.util etc. 2.)User defined packages To define user defined packages, “package" keyword is used. Syntax:­ package <package name>; For example:­ package inter; public interface test1 { public void test1(); public void test2(); } EXCEPTIONS EXCEPTIONS An exception is a condition that cannot be resolved within the context of the operation that caused it. (examples?) To throw an exception is to signal that such a condition has occurred. To catch an exception is to transfer control to an exception handling routine, altering the normal execution flow of the program. Because exceptions are outside the normal operation of a program the normal, default action is to write out an error message and terminate the offending process. import javax.swing.JOptionPane; import javax.swing.JOptionPane; public class DivideByZeroTest { public static void main (String args) { String firstNumber, secondNumber; int number1, number2, result; firstNumber = JOptionPane.showInputDialog ( "Enter dividend integer"); secondNumber = JOptionPane.showInputDialog ( "Enter divisor integer"); try { number1 = Integer.parseInt (firstNumber); number2 = Integer.parseInt (secondNumber); result = number1 / number2; JOptionPane.showMessageDialog (null, "The result is " + result, "Results", JOptionPane.PLAIN_MESSAGE); } catch (NumberFormatException numberFormatException) { JOptionPane.showMessageDialog (null, "You must enter two integers", "Invalid Number Format", JOptionPane.ERROR_MESSAGE); } System.exit(0); }//end of main }//end of class DivideByZeroTest APPLETS APPLETS An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page to tell the browser about the applet You don’t need to supply a main method; the browser does that • When you write an applet, you are writing only part of a program • You supply certain methods that the browser calls For security reasons, applets run in a sandbox: they have no access to the client’s file system THE SIMPLEST APPLET THE SIMPLEST APPLET import java.awt.*; import javax.swing.JApplet; public class HelloWorld extends JApplet { public void paint(Graphics g) { g.drawString("Hello World!", 30, 30); } } STREAMS STREAMS Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) • it acts as a buffer between the data source and destination Input stream: a stream that provides input to a program • System.in is an input stream Output stream: a stream that accepts output from a program • System.out is an output stream A stream connects a program to an I/O object • System.out connects a program to the screen • System.in connects a program to the keyboard INPUT AND OUTPUT INPUT AND OUTPUT data source: input device device driver input library our program our program output library device driver data destination: Output device MULTI­THREADING MULTI­THREADING The ability of an operating system to execute different parts of a program, called threads, simultaneously. The programmer must carefully design the program in such a way that all the threads can run at the same time without interfering with each other. ADVANTAGES OF MULTI­THREADING:­ ADVANTAGES OF MULTI­THREADING:­ If a thread can not use all the computing resources of the CPU (because instructions depend on each other's result), running another thread permits to not leave these idle. DISADVANTAGES OF MULTI­THREADING:­ Hardware support for Multithreading is more visible to software, thus requiring more changes to both application programs and operating systems than Multiprocessing. ...
View Full Document

Ask a homework question - tutors are online