Jagannath Institute of Management Sciences Lajpat Nagar

Size: px
Start display at page:

Download "Jagannath Institute of Management Sciences Lajpat Nagar"

Transcription

1 Jagannath Institute of Management Sciences Lajpat Nagar BCA Sem V JAVA

2 UNIT I (8 Lectures) The Genesis of Java: Why Java? Flavors of Java. Java Designing Goal. Role of Java Programmer in Industry. Features of Java Language.JVM The heart of Java, Java s Magic Byte code, using blocks of code, the Java libraries. Java Programming: Data types (Primitive and Reference), Control structured (Decision making, looping, branching statements), Arrays (One and two dimensional), Introducing classes and objects. About Java Java is a programming language and a platform. Java is a high level, robust, secured and object-oriented programming language. Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has its own runtime environment (JRE) and API, it is called platform. Where it is used? According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of them are as follows: 1. Desktop Applications such as acrobat reader, media player, antivirus etc. 2. Web Applications such as irctc.co.in, javatpoint.com etc. 3. Enterprise Applications such as banking applications. 4. Mobile 5. Embedded System 6. Smart Card 7. Robotics 8. Games etc. Types of Java Applications

3 There are mainly 4 type of applications that can be created using java programming: 1) Standalone Application It is also known as desktop application or window-based application. An application that we need to install on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone applications. 2) Web Application An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java. 3) Enterprise Application An application that is distributed in nature, such as banking applications etc. It has the advantage of high level security, load balancing and clustering. In java, EJB is used for creating enterprise applications. 4) Mobile Application An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications. History of Java Java history is interesting to know. The history of java starts from Green Team. Java team members (also known as Green Team), initiated a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc. For the green team members, it was an advance concept at that time. But, it was suited for internet programming. Later, Java technology as incorporated by Netscape. Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are given the major points that describes the history of java. 1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June The small team of sun engineers called Green Team.

4 2) Originally designed for small, embedded systems in electronic appliances like settop boxes. 3) Firstly, it was called "Greentalk" by James Gosling and file extension was.gt. 4) After that, it was called Oak and was developed as a part of the Green project. Why Oak name for java language? 5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A., France, Germany, Romania etc. 6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies. Why Java name for java language? 7) Why they choosed java name for java language? The team gathered to choose a new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say. According to James Gosling "Java was one of the top choices along with Silk". Since java was so unique, most of the team members preferred java. 8) Java is an island of Indonesia where first coffee was produced (called java coffee). 9) Notice that Java is just a name not an acronym. 10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in ) In 1995, Time magazine called Java one of the Ten Best Products of ) JDK 1.0 released in(january 23, 1996). Java Version History There are many java versions that has been released. Current stable release of Java is Java SE 8.

5 1. JDK Alpha and Beta (1995) 2. JDK 1.0 (23rd Jan, 1996) 3. JDK 1.1 (19th Feb, 1997) 4. J2SE 1.2 (8th Dec, 1998) 5. J2SE 1.3 (8th May, 2000) 6. J2SE 1.4 (6th Feb, 2002) 7. J2SE 5.0 (30th Sep, 2004) 8. Java SE 6 (11th Dec, 2006) 9. Java SE 7 (28th July, 2011) 10. Java SE 8 (18th March, 2014) Features of Java There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple and easy to understand. 1. Simple 2. Object-Oriented 3. Platform independent 4. Secured 5. Robust 6. Architecture neutral 7. Portable 8. Dynamic 9. Interpreted 10. High Performance 11. Multithreaded 12. Distributed Simple According to Sun, Java language is simple because: 1. syntax is based on C++ (so easier for programmers to learn it after C++). 2. removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc. 3. No need to remove unreferenced objects because there is Automatic Garbage

6 Collection in java. Object-oriented Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behavior. Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. Basic concepts of OOPs are: 1. Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation Platform Independent A platform is the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform. The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms. It has two components: 1. Runtime Environment 2. API(Application Programming Interface)

7 Java code can be run on multiple platforms e.g.windows, Linux, Sun Solaris, and Mac/OS etc. Java code is compiled by the compiler and converted into bytecode.this byte code is a platform independent code because it can be run on multiple platforms i.e. Write Once and Run Anywhere (WORA). Secured Java is secured because: No explicit pointer Programs run inside virtual machine sandbox. Class loader- adds security by separating the package for the classes of the local file system from those that are imported from network sources.

8 Byte code Verifier- checks the code fragments for illegal code that can violate access right to objects. Security Manager- determines what resources a class can access such as reading and writing to the local disk. These securities are provided by java language. Some security can also be provided by application developer through SSL,JAAS,cryptography etc. Robust Robust simply means strong. Java uses strong memory management. There is lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points make java robust. Architecture-neutral There are no implementation dependent features e.g. size of primitive types is set. Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system. Portable We may carry the java bytecode to any platform. Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset. High-performance Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++) Distributed We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet. Multi-threaded

9 A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares the same memory. Threads are important for multimedia, Web applications etc. Interpreted Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process. Dynamic Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time. Simple Program of Java 1. class Simple 2. { 3. public static void main(string args[]) 4. { 5. System.out.println("Hello Java"); Save this file as Simple.java To compile: javac Simple.java To execute: java Simple Output:Hello Java Understanding first java program

10 The meaning of class, public, static, void, main, String[], System.out.println(). class keyword is used to declare a class in java. public keyword is an access modifier which represents visibility, it means it is visible to all. static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory. void is the return type of the method, it means it doesn't return any value. main represents startup of the program. String[] args is used for command line argument. We will learn it later. System.out.println() is used print statement. To write the simple program, open notepad by start menu -> All Programs - > Accessories -> notepad and write simple program as displayed below: As displayed in the above diagram, write the simple program of java in notepad and saved it as Simple.java. To compile and run this program, you need to open command prompt by start menu -> All Programs -> Accessories -> command prompt.

11 To compile and run the above program, go to your current directory first; my current directory is c:\new. Write here: To compile: javac Simple.java To execute: java Simple Different Ways to write a java program There are many ways to write a java program. The modifications that can be done in a java program are given below:

12 1) By changing sequence of the modifiers, method prototype is not changed. Let's see the simple code of main method. 1. static public void main(string args[]) 2) subscript notation in java array can be used after type, before variable or after variable. Let's see the different codes to write the main method. 1. public static void main(string[] args) 2. public static void main(string []args) 3. public static void main(string args[]) 3) You can provide var-args support to main method by passing 3 ellipses (dots) Let's see the simple code of using var-args in main method. We will learn about var-args later in Java New Features chapter. 1. public static void main(string... args) 4) Having semicolon at the end of class in java is optional. Let's see the simple code. 1. class A{ 2. static public void main(string... args){ 3. System.out.println("hello java4"); ; Valid java main method signature 1. public static void main(string[] args) 2. public static void main(string []args) 3. public static void main(string args[]) 4. public static void main(string... args) 5. static public void main(string[] args) 6. public static final void main(string[] args) 7. final public static void main(string[] args) 8. final strictfp public static void main(string[] args) Invalid java main method signature

13 1. public void main(string[] args) 2. static void main(string[] args) 3. public void static main(string[] args) 4. abstract public static void main(string[] args) Resolving an error "javac is not recognized as an internal or external command"? Since DOS doesn't know javac or java, we need to set path. Path is not required in such a case if you save your program inside the jdk/bin folder. But its good approach to set path. Click here for How to set path in java.

14 How to set path in Java 1. How to set path of JDK in Windows OS 1. Setting Temporary Path of JDK 2. Setting Permanent Path of JDK 2. How to set path of JDK in Linux OS The path is required to be set for using tools such as javac, java etc. If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all the tools will be available in the current directory. But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK. There are 2 ways to set java path: 1. temporary 2. permanent 1) How to set Temporary Path of JDK in Windows To set the temporary path of JDK, you need to follow following steps: Open command prompt copy the path of jdk/bin directory write in command prompt: set path=copied_path For Example: set path=c:\program Files\Java\jdk1.6.0_23\bin Let's see it in the figure given below:

15 2) How to set Permanent Path of JDK in Windows For setting the permanent path of JDK, you need to follow these steps: Go to MyComputer properties -> advanced tab -> environment variables - > new tab of user variable -> write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok For Example: 1)Go to MyComputer properties

16 2)click on advanced tab

17 3)click on environment variables 4)click on new tab of user variables

18 5)write path in variable name

19 6)Copy the path of bin folder 7)paste path of bin folder in variable value

20 8)click on ok button

21 9)click on ok button

22 Now your permanent path is set. You can now execute any program of java from any drive. What happens at compile time? At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the java code into bytecode.

23 What happens at runtime? At runtime, following steps are performed: Classloader: is the subsystem of JVM that is used to load class files. Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects. Interpreter: read bytecode stream then execute the instructions. Can you save a java source file by other name than the class name? Yes, if the class is not public. It is explained in the figure given below:

24 To compile: javac Hard.java To execute: java Simple Can you have multiple classes in a java source file? Yes, like the figure given below illustrates:

25 Difference between JDK, JRE and JVM Understanding the difference between JDK, JRE and JVM is important in Java. We are having brief overview of JVM here. If you want to get the detailed knowledge of Java Virtural Machine, move to the next page. Firstly, let's see the basic differences between the JDK, JRE and JVM. JVM JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent. The JVM performs following main tasks: Loads code Verifies code Executes code Provides runtime environment JRE JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.it is the implementation of JVM.It physically exists.it contains set of libraries + other files that JVM uses at runtime. Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

26 JDK JDK is an acronym for Java Development Kit.It physically exists.it contains JRE + development tools.

27 JVM (Java Virtual Machine) JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms (i.e.jvm is plateform dependent). What is JVM? It is: 1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies. 2. An implementation Its implementation is known as JRE (Java Runtime Environment). 3. Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created. What it does? The JVM performs following operation: Loads code Verifies code Executes code Provides runtime environment JVM provides definitions for the: Memory area Class file format Register set Garbage-collected heap Fatal error reporting etc. Internal Architecture of JVM Let's understand the internal architecture of JVM. It contains classloader, memory

28 area, execution engine etc. 1) Classloader: Classloader is a subsystem of JVM that is used to load class files. 2) Class(Method) Area: Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods. 3) Heap: It is the runtime data area in which objects are allocated.

29 4) Stack: Java Stack stores frames.it holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes. 5) Program Counter Register: PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed. 6) Native Method Stack: It contains all the native methods used in the application. 7) Execution Engine: It contains: 1) A virtual processor 2) Interpreter:Read bytecode stream then execute the instructions. 3) Just-In-Time(JIT) compiler:it is used to improve the performance.jit compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.here the term?compiler? refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU. Java - Basic Syntax When we consider a Java program it can be defined as a collection of objects that communicate via invoking each other's methods.

30 Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support. Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables. Basic Syntax: About Java programs, it is very important to keep in mind the following points. Case Sensitivity - Java is case sensitive, which means identifierhello and hello would have different meaning in Java. Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example class MyFirstJavaClass Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void mymethodname() Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile).

31 Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' public static void main(string args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program.. Java Identifiers: All Java components require names. Names used for classes, variables and methods are called identifiers. In Java, there are several points to remember about identifiers. They are as follows: All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). After the first character identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, 1_value Examples of illegal identifiers: 123abc, -salary Java Modifiers: Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers: Access Modifiers: default, public, protected, private Non-access Modifiers: final, abstract, strictfp Java Keywords: The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break

32 byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Comments in Java Java supports single-line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler. public class MyFirstJavaProgram{ /* This is my first java program. * This will print 'Hello World' as the output

33 * This is an example of multi-line comments. */ public static void main(string []args){ // This is an example of single line comment /* This is also an example of single line comment. */ System.out.println("Hello World"); Using Blank Lines: A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it. Java Naming conventions Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method etc. But, it is not forced to follow. So, it is known as convention not rule. All the classes, interfaces, packages, methods and fields of java programming language are given according to java naming convention. Advantage of naming conventions in java By using standard Java naming conventions, you make your code easier to read for yourself and for other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does. Name Convention

34 class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc. interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc. method name should start with lowercase letter and be a verb e.g. actionperformed(), main(), print(), println() etc. variable name should start with lowercase letter e.g. firstname, ordernumber etc. package name should be in lowercase letter e.g. java, lang, sql, util etc. constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc. CamelCase in java naming conventions Java follows camelcase syntax for naming the class, interface, method and variable. If name is combined with two words, second word will start with uppercase letter always e.g. actionperformed(), firstname, ActionEvent, ActionListener etc. Java - Variable Types A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

35 You must declare all variables before they can be used. The basic form of a variable declaration is shown here: data type variable [ = value][, variable [= value]...] ; Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list. Following are valid examples of variable declaration and initialization in Java: int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = ; // declares and assigns a value of PI. char a = 'a'; // the char variable a iis initialized with value 'a' This chapter will explain various variable types available in Java Language. There are three kinds of variables in Java: Local variables Instance variables Class/static variables

36 Local variables: Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor or block. Local variables are implemented at stack level internally. There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use. Example: Here, age is a local variable. This is defined inside pupage() method and its scope is limited to this method only. public class Test{ public void pupage(){ int age = 0; age = age + 7; System.out.println("Puppy age is : " + age); public static void main(string args[]){ Test test = new Test(); test.pupage();

37 This would produce the following result: Puppy age is: 7 Example: Following example uses age without initializing it, so it would give an error at the time of compilation. public class Test{ public void pupage(){ int age; age = age + 7; System.out.println("Puppy age is : " + age); public static void main(string args[]){ Test test = new Test(); test.pupage(); This would produce the following error while compiling it: Test.java:4:variable number might not have been initialized age = age + 7; ^ 1 error Instance variables: Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.

38 Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared in class level before or after use. Access modifiers can be given for instance variables. The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However visibility for subclasses can be given for these variables with the use of access modifiers. Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) should be called using the fully qualified name.objectreference.variablename. Example: import java.io.*; public class Employee{ // this instance variable is visible for any child class. public String name; // salary variable is visible in Employee class only. private double salary; // The name variable is assigned in the constructor. public Employee (String empname){ name = empname; // The salary variable is assigned a value. public void setsalary(double empsal){

39 salary = empsal; // This method prints the employee details. public void printemp(){ System.out.println("name : " + name ); System.out.println("salary :" + salary); public static void main(string args[]){ Employee empone = new Employee("Ransika"); empone.setsalary(1000); empone.printemp(); This would produce the following result: name : Ransika salary : Class/static variables: Class variables also known as static variables are declared with thestatic keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value. Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops.

40 Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally values can be assigned in special static initializer blocks. Static variables can be accessed by calling with the class name.classname.variablename. When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables. Example: import java.io.*; public class Employee{ // salary variable is a private static variable private static double salary; // DEPARTMENT is a constant public static final String DEPARTMENT = "Development "; public static void main(string args[]){ salary = 1000; System.out.println(DEPARTMENT+"average salary:"+salary); This would produce the following result: Development average salary:1000 Note: If the variables are access from an outside class the constant should be accessed as Employee.DEPARTMENT

41 Example to understand the types of variables copy to clipboard 1. class A{ 2. int data=50;//instance variable 3. static int m=100;//static variable 4. void method(){ 5. int n=90;//local variable //end of class Java - Basic Datatypes Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. There are two data types available in Java: Primitive Data Types Reference/Object Data Types or Non Primitive Data Types

42 Data Type Default Value Default size boolean false 1 bit char '\u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte

43 double 0.0d 8 byte Primitive Data Types: There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a keyword. Let us now look into detail about the eight primitive data types. byte: Byte data type is an 8-bit signed two's complement integer. Minimum value is -128 (-2^7) Maximum value is 127 (inclusive)(2^7-1) Default value is 0 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int. Example: byte a = 100, byte b = -50 short: Short data type is a 16-bit signed two's complement integer. Minimum value is -32,768 (-2^15) Maximum value is 32,767 (inclusive) (2^15-1) Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int Default value is 0. Example: short s = 10000, short r = int: Int data type is a 32-bit signed two's complement integer. Minimum value is - 2,147,483,648.(-2^31)

44 Maximum value is 2,147,483,647(inclusive).(2^31-1) Int is generally used as the default data type for integral values unless there is a concern about memory. The default value is 0. Example: int a = , int b = long: Long data type is a 64-bit signed two's complement integer. Minimum value is -9,223,372,036,854,775,808.(-2^63) Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63-1) This type is used when a wider range than int is needed. Default value is 0L. Example: long a = L, int b = L float: Float data type is a single-precision 32-bit IEEE 754 floating point. Float is mainly used to save memory in large arrays of floating point numbers. Default value is 0.0f. Float data type is never used for precise values such as currency. Example: float f1 = 234.5f double: double data type is a double-precision 64-bit IEEE 754 floating point. This data type is generally used as the default data type for decimal values, generally the default choice. Double data type should never be used for precise values such as currency. Default value is 0.0d.

45 Example: double d1 = boolean: boolean data type represents one bit of information. There are only two possible values: true and false. This data type is used for simple flags that track true/false conditions. Default value is false. Example: boolean one = true char: char data type is a single 16-bit Unicode character. Minimum value is '\u0000' (or 0). Maximum value is '\uffff' (or 65,535 inclusive). Char data type is used to store any character. Example: char lettera ='A' Reference Data Types: Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc. Class objects, and various type of array variables come under reference data type. Default value of any reference variable is null. A reference variable can be used to refer to any object of the declared type or any compatible type. Example: Animal animal = new Animal("giraffe");

46 Java Literals: A literal is a source code representation of a fixed value. They are represented directly in the code without any computation. Literals can be assigned to any primitive type variable. For example: byte a = 68; char a = 'A' byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number systems as well. Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems for literals. For example: int decimal = 100; int octal = 0144; int hexa = 0x64; String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are: "Hello World" "two\nlines" "\"This is in quotes\"" String and char types of literals can contain any Unicode characters. For example: char a = '\u0001'; String a = "\u0001";

47 Java language supports few special escape sequences for String and char literals as well. They are: Notation Character represented \n Newline (0x0a) \r Carriage return (0x0d) \f Formfeed (0x0c) \b Backspace (0x08) \s Space (0x20) \t tab \" Double quote \' Single quote \\ backslash \ddd Octal character (ddd) \uxxxx Hexadecimal UNICODE character (xxxx) Unicode System Unicode is a universal international standard character encoding that is capable of representing most of the world's written languages.

48 Why java uses Unicode System? Before Unicode, there were many language standards: ASCII (American Standard Code for Information Interchange) for the United States. ISO for Western European Language. KOI-8 for Russian. GB18030 and BIG-5 for chinese, and so on. This caused two problems: 1. A particular code value corresponds to different letters in the various language standards. 2. The encodings for languages with large character sets have variable length. Some common characters are encoded as single bytes, other require two or more byte. To solve these problems, a new language standard was developed i.e. Unicode System. In unicode, character holds 2 byte, so java also uses 2 byte for characters. Java - Basic Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Misc Operators

49 The Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Assume integer variable A holds 10 and variable B holds 20, then: Show Examples Operator Description Example + Addition - Adds values on either side of the operator A + B will give 30 - Subtraction - Subtracts right hand operand from left hand A - B will give -10 operand * Multiplication - Multiplies values on either side of the operator A * B will give 200 / Division - Divides left hand operand by right hand operand B / A will give 2 % Modulus - Divides left hand operand by right hand operand B % A will give 0 and returns remainder ++ Increment - Increases the value of operand by 1 B++ gives Decrement - Decreases the value of operand by 1 B-- gives 19

50 The Relational Operators: There are following relational operators supported by Java language Assume variable A holds 10 and variable B holds 20, then: Operator Description Example == Checks if the values of two operands are equal or (A == B) is not true. not, if yes then condition becomes true.!= Checks if the values of two operands are equal or (A!= B) is true. not, if values are not equal then condition becomes true. > Checks if the value of left operand is greater than the (A > B) is not true. value of right operand, if yes then condition becomes true. < Checks if the value of left operand is less than the (A < B) is true. value of right operand, if yes then condition becomes true. >= Checks if the value of left operand is greater than or (A >= B) is not true. equal to the value of right operand, if yes then condition becomes true. <= Checks if the value of left operand is less than or (A <= B) is true. equal to the value of right operand, if yes then condition becomes true.

51 The Bitwise Operators: Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows: a = b = a&b = a b = a^b = ~a = The following table lists the bitwise operators: Assume integer variable A holds 60 and variable B holds 13 then: Operator Description Example & Binary AND (A & B) will give 12 which is Operator copies a bit to the result if it exists in both operands. Binary OR (A B) will give 61 which is Operator copies a bit

52 if it exists in either operand. ^ Binary XOR (A ^ B) will give 49 which is Operator copies the bit if it is set in one operand but not both. ~ Binary Ones (~A ) will give -61 which is in 2's complement form due Complement to a signed binary number. Operator is unary and has the effect of 'flipping' bits. << Binary Left A << 2 will give 240 which is Shift Operator. The left operands value is moved left by the number of bits specified by the right operan

53 >> Binary Right A >> 2 will give 15 which is 1111 Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. >>> Shift right A >>>2 will give 15 which is zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

54 The Logical Operators: The following table lists the logical operators: Assume Boolean variables A holds true and variable B holds false, then: Operator Description Example && Called Logical AND operator. If both the (A && B) is false. operands are non-zero, then the condition becomes true. Called Logical OR Operator. If any of the two (A B) is true. operands are non-zero, then the condition becomes true.! Called Logical NOT Operator. Use to reverses!(a && B) is true. the logical state of its operand. If a condition is true then Logical NOT operator will make false. The Assignment Operators: There are following assignment operators supported by Java language: Operator Description Example = Simple assignment C = A + B will assign value of A + B into C operator, Assigns values from right side operands to left side operand += Add AND assignment C += A is equivalent to C = C + A operator, It adds right operand to the left operand and assign the result to left

55 operand -= Subtract AND C -= A is equivalent to C = C - A assignment operator, It subtracts right operand from the left operand and assign the result to left operand *= Multiply AND C *= A is equivalent to C = C * A assignment operator, It multiplies right operand with the left operand and assign the result to left operand /= Divide AND C /= A is equivalent to C = C / A assignment operator, It divides left operand with the right operand and assign the result to left operand %= Modulus AND C %= A is equivalent to C = C % A assignment operator, It takes modulus using two operands and assign the result to left operand <<= Left shift AND C <<= 2 is same as C = C << 2 assignment operator >>= Right shift AND C >>= 2 is same as C = C >> 2 assignment operator &= Bitwise AND C &= 2 is same as C = C & 2

56 assignment operator ^= bitwise exclusive OR C ^= 2 is same as C = C ^ 2 and assignment operator = bitwise inclusive OR C = 2 is same as C = C 2 and assignment operator Misc Operators There are few other operators supported by Java Language. Conditional Operator (? : ): Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as: variable x = (expression)? value if true : value if false Following is the example: public class Test { public static void main(string args[]){ int a, b; a = 10; b = (a == 1)? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10)? 20: 30;

57 System.out.println( "Value of b is : " + b ); This would produce the following result: Value of b is : 30 Value of b is : 20 instanceof Operator: This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceof operator is wriiten as: ( Object reference variable ) instanceof (class/interface type) If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example: public class Test { public static void main(string args[]){ String name = "James"; // following will return true since name is type of String boolean result = name instanceof String; System.out.println( result ); This would produce the following result: true

58 This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example: class Vehicle { public class Car extends Vehicle { public static void main(string args[]){ Vehicle a = new Car(); boolean result = a instanceof Car; System.out.println( result ); This would produce the following result: true Precedence of Java Operators: Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator: For example, x = * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Category Operator Associativity Postfix () []. (dot operator) Left toright

59 Unary ! ~ Right to left Multiplicative * / % Left to right Additive + - Left to right Shift >> >>> << Left to right Relational > >= < <= Left to right Equality ==!= Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR Left to right Logical AND && Left to right Logical OR Left to right Conditional?: Right to left Assignment = += -= *= /= %= >>= <<= &= ^= = Right to left Comma, Left to right

60 Java - Decision Making There are two types of decision making statements in Java. They are: if statements switch statements The if Statement: An if statement consists of a Boolean expression followed by one or more statements. Syntax: The syntax of an if statement is: if(boolean_expression) { //Statements will execute if the Boolean expression is true If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed. Example: public class Test { public static void main(string args[]){ int x = 10; if( x < 20 ){ System.out.print("This is if statement"); This would produce the following result:

61 This is if statement The if...else Statement: An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax: The syntax of an if...else is: if(boolean_expression){ //Executes when the Boolean expression is true else{ //Executes when the Boolean expression is false Example: public class Test { public static void main(string args[]){ int x = 30; if( x < 20 ){ System.out.print("This is if statement"); else{ System.out.print("This is else statement"); This would produce the following result: This is else statement The if...else if...else Statement: An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

62 When using if, else if, else statements there are few points to keep in mind. An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Syntax: The syntax of an if...else is: if(boolean_expression 1){ //Executes when the Boolean expression 1 is true else if(boolean_expression 2){ //Executes when the Boolean expression 2 is true else if(boolean_expression 3){ //Executes when the Boolean expression 3 is true else { //Executes when the none of the above condition is true. Example: public class Test { public static void main(string args[]){ int x = 30; if( x == 10 ){ System.out.print("Value of X is 10"); else if( x == 20 ){ System.out.print("Value of X is 20"); else if( x == 30 ){ System.out.print("Value of X is 30"); else{ System.out.print("This is else statement");

63 This would produce the following result: Value of X is 30 Nested if...else Statement: It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement. Syntax: The syntax for a nested if...else is as follows: if(boolean_expression 1){ //Executes when the Boolean expression 1 is true if(boolean_expression 2){ //Executes when the Boolean expression 2 is true You can nest else if...else in the similar way as we have nested if statement. Example: public class Test { public static void main(string args[]){ int x = 30; int y = 10; if( x == 30 ){ if( y == 10 ){ System.out.print("X = 30 and Y = 10");

64 This would produce the following result: X = 30 and Y = 10 The switch Statement: A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. Syntax: The syntax of enhanced for loop is: switch(expression){ case value : //Statements break; //optional case value : //Statements break; //optional //You can have any number of case statements. default : //Optional //Statements The following rules apply to a switch statement: The variable used in a switch statement can only be a byte, short, int, or char. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

65 Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. Example: public class Test { public static void main(string args[]){ //char grade = args[0].charat(0); char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); System.out.println("Your grade is " + grade);

66 Compile and run above program using various command line arguments. This would produce the following result: $ java Test Well done Your grade is a C $ Java - Loop Control There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops: while Loop do...while Loop for Loop As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays. The while Loop: A while loop is a control structure that allows you to repeat a task a certain number of times. Syntax: The syntax of a while loop is: while(boolean_expression) { //Statements When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

67 Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Example: public class Test { public static void main(string args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 The do...while Loop:

68 A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax: The syntax of a do...while loop is: do { //Statements while(boolean_expression); Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false. Example: public class Test { public static void main(string args[]){ int x = 10; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); while( x < 20 ); This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13

69 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 The for Loop: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax: The syntax of a for loop is: for(initialization; Boolean_expression; update) { //Statements Here is the flow of control in a for loop: The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

70 Example: public class Test { public static void main(string args[]) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 Enhanced for loop in Java: As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays. Syntax:

71 The syntax of enhanced for loop is: for(declaration : expression) { //Statements Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array. Example: public class Test { public static void main(string args[]){ int [] numbers = {10, 20, 30, 40, 50; for(int x : numbers ){ System.out.print( x ); System.out.print(","); System.out.print("\n"); String [] names ={"James", "Larry", "Tom", "Lacy"; for( String name : names ) { System.out.print( name ); System.out.print(","); This would produce the following result: 10,20,30,40,50, James,Larry,Tom,Lacy,

72 The break Keyword: The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax: The syntax of a break is a single statement inside any loop: break; Example: public class Test { public static void main(string args[]) { int [] numbers = {10, 20, 30, 40, 50; for(int x : numbers ) { if( x == 30 ) { break; System.out.print( x ); System.out.print("\n"); This would produce the following result: 10 20

73 The continue Keyword: The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: The syntax of a continue is a single statement inside any loop: continue; Example: public class Test { public static void main(string args[]) { int [] numbers = {10, 20, 30, 40, 50; for(int x : numbers ) { if( x == 30 ) { continue; System.out.print( x ); System.out.print("\n"); This would produce the following result:

74 Java - Object & Classes Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts: Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method Message Parsing The concepts Classes and Objects. Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/blue print that describes the behaviors/states that object of its type support. Objects in Java: Let us now look deep into what are objects. If we consider the real-world we can find many objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior. If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging, running If you compare the software object with a real world object, they have very similar characteristics. Software objects also have a state and behavior. A software object's state is stored in fields and behavior is shown via methods. So in software development, methods operate on the internal state of an object and the object-toobject communication is done via methods.

75 Classes in Java: A class is a blue print from which individual objects are created. A sample of a class is given below: public class Dog{ String breed; int age; String color; void barking(){ void hungry(){ void sleeping(){ A class can contain any of the following variable types. Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Class variables: Class variables are variables declared with in a class, outside any method, with the static keyword. A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods. Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language.

76 Java - Numbers Class Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc. Example: int i = 5000; float gpa = 13.65; byte mask = 0xaf; However, in development, we come across situations where we need to use objects instead of primitive data types. In-order to achieve this Java provides wrapper classes for each primitive data type. All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number. This wrapping is taken care of by the compiler, the process is called boxing. So when a primitive is used when an object is required, the compiler boxes the primitive type in its wrapper class. Similarly, the compiler unboxes the object to a primitive as well. The Number is part of the java.lang package. Here is an example of boxing and unboxing: public class Test{ public static void main(string args[]){ Integer x = 5; // boxes int to an Integer object x = x + 10; // unboxes the Integer to a int System.out.println(x);

77 This would produce the following result: 15 When x is assigned integer values, the compiler boxes the integer because x is integer objects. Later, x is unboxed so that they can be added as integers. Number Methods: Here is the list of the instance methods that all the subclasses of the Number class implement: SN Methods with Description 1 xxxvalue() Converts the value of this Number object to the xxx data type and returned it. 2 compareto() Compares this Number object to the argument. 3 equals() Determines whether this number object is equal to the argument. 4 valueof() Returns an Integer object holding the value of the specified primitive. 5 tostring() Returns a String object representing the value of specified int or Integer. 6 parseint()

78 This method is used to get the primitive data type of a certain String. 7 abs() Returns the absolute value of the argument. 8 ceil() Returns the smallest integer that is greater than or equal to the argument. Returned as a double. 9 floor() Returns the largest integer that is less than or equal to the argument. Returned as a double. 10 rint() Returns the integer that is closest in value to the argument. Returned as a double. 11 round() Returns the closest long or int, as indicated by the method's return type, to the argument. 12 min() Returns the smaller of the two arguments. 13 max() Returns the larger of the two arguments. 14 exp() Returns the base of the natural logarithms, e, to the power of the argument.

79 15 log() Returns the natural logarithm of the argument. 16 pow() Returns the value of the first argument raised to the power of the second argument. 17 sqrt() Returns the square root of the argument. 18 sin() Returns the sine of the specified double value. 19 cos() Returns the cosine of the specified double value. 20 tan() Returns the tangent of the specified double value. 21 asin() Returns the arcsine of the specified double value. 22 acos() Returns the arccosine of the specified double value. 23 atan() Returns the arctangent of the specified double value.

80 24 atan2() Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta. 25 todegrees() Converts the argument to degrees 26 toradians() Converts the argument to radians. 27 random() Returns a random number. Java - Character Class Normally, when we work with characters, we use primitive data types char. Example: char ch = 'a'; // Unicode for uppercase Greek omega character char unichar = '\u039a'; // an array of chars char[] chararray ={ 'a', 'b', 'c', 'd', 'e' ;

81 However in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper class Character for primitive data type char. The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor: Character ch = new Character('a'); The Java compiler will also create a Character object for you under some circumstances. For example, if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes the other way. Example: // Here following primitive char 'a' // is boxed into the Character object ch Character ch = 'a'; // Here primitive 'x' is boxed for method test, // return is unboxed to char 'c' char c = test('x'); Escape Sequences: A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The newline character (\n) has been used frequently in this tutorial in System.out.println() statements to advance to the next line after the string is printed. Following table shows the Java escape sequences:

82 Escape Sequence Description \t Inserts a tab in the text at this point. \b Inserts a backspace in the text at this point. \n Inserts a newline in the text at this point. \r Inserts a carriage return in the text at this point. \f Inserts a form feed in the text at this point. \' Inserts a single quote character in the text at this point. \" Inserts a double quote character in the text at this point. \\ Inserts a backslash character in the text at this point. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. Example: If you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes: public class Test { public static void main(string args[]) { System.out.println("She said \"Hello!\" to me."); This would produce the following result: She said "Hello!" to me.

83 Character Methods: Here is the list of the important instance methods that all the subclasses of the Character class implement: SN Methods with Description 1 isletter() Determines whether the specified char value is a letter. 2 isdigit() Determines whether the specified char value is a digit. 3 iswhitespace() Determines whether the specified char value is white space. 4 isuppercase() Determines whether the specified char value is uppercase. 5 islowercase() Determines whether the specified char value is lowercase. 6 touppercase() Returns the uppercase form of the specified char value. 7 tolowercase() Returns the lowercase form of the specified char value.

84 8 tostring() Returns a String object representing the specified character valuethat is, a one-character string. For a complete list of methods, please refer to the java.lang.character API specification. Java - Strings Class Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. Creating Strings: The most direct way to create a string is to write: String greeting = "Hello world!"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters. public class StringDemo{ public static void main(string args[]){ char[] helloarray = { 'h', 'e', 'l', 'l', 'o', '.'; String hellostring = new String(helloArray); System.out.println( hellostring ); This would produce the following result: hello.

85 Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes. String Length: Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17: public class StringDemo { public static void main(string args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); This would produce the following result: String Length is : 17 Concatenating Strings: The String class includes a method for concatenating two strings: string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in: "My name is ".concat("zara"); Strings are more commonly concatenated with the + operator, as in: "Hello," + " world" + "!" which results in:

86 "Hello, world!" Let us look at the following example: public class StringDemo { public static void main(string args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); This would produce the following result: Dot saw I was Tod Creating Format Strings: You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of: System.out.printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatvar, intvar, stringvar); you can write: String fs; fs = String.format("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatvar, intvar, stringvar); System.out.println(fs); String Methods: Here is the list of methods supported by String class:

87 SN Methods with Description 1 char charat(int index) Returns the character at the specified index. 2 int compareto(object o) Compares this String to another Object. 3 int compareto(string anotherstring) Compares two strings lexicographically. 4 int comparetoignorecase(string str) Compares two strings lexicographically, ignoring case differences. 5 String concat(string str) Concatenates the specified string to the end of this string. 6 boolean contentequals(stringbuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. 7 static String copyvalueof(char[] data) Returns a String that represents the character sequence in the array specified. 8 static String copyvalueof(char[] data, int offset, int count) Returns a String that represents the character sequence in the array specified.

88 9 boolean endswith(string suffix) Tests if this string ends with the specified suffix. 10 boolean equals(object anobject) Compares this string to the specified object. 11 boolean equalsignorecase(string anotherstring) Compares this String to another String, ignoring case considerations. 12 byte getbytes() Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. 13 byte[] getbytes(string charsetname Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. 14 void getchars(int srcbegin, int srcend, char[] dst, int dstbegin) Copies characters from this string into the destination character array. 15 int hashcode() Returns a hash code for this string. 16 int indexof(int ch) Returns the index within this string of the first occurrence of the specified character. 17 int indexof(int ch, int fromindex) Returns the index within this string of the first occurrence of the specified character,

89 starting the search at the specified index. 18 int indexof(string str) Returns the index within this string of the first occurrence of the specified substring. 19 int indexof(string str, int fromindex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index 20 String intern() Returns a canonical representation for the string object. 21 int lastindexof(int ch) Returns the index within this string of the last occurrence of the specified character. 22 int lastindexof(int ch, int fromindex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. 23 int lastindexof(string str) Returns the index within this string of the rightmost occurrence of the specified substring. 24 int lastindexof(string str, int fromindex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. 25 int length()

90 Returns the length of this string. 26 boolean matches(string regex) Tells whether or not this string matches the given regular expression. 27 boolean regionmatches(boolean ignorecase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal. 28 boolean regionmatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal 29 String replace(char oldchar, char newchar) Returns a new string resulting from replacing all occurrences of oldchar in this string with newchar. 30 String replaceall(string regex, String replacement Replaces each substring of this string that matches the given regular expression with the given replacement. 31 String replacefirst(string regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement. 32 String[] split(string regex) Splits this string around matches of the given regular expression. 33 String[] split(string regex, int limit)

91 Splits this string around matches of the given regular expression. 34 boolean startswith(string prefix) Tests if this string starts with the specified prefix. 35 boolean startswith(string prefix, int toffset) Tests if this string starts with the specified prefix beginning a specified index. 36 CharSequence subsequence(int beginindex, int endindex) Returns a new character sequence that is a subsequence of this sequence. 37 String substring(int beginindex) Returns a new string that is a substring of this string. 38 String substring(int beginindex, int endindex) Returns a new string that is a substring of this string. 39 char[] tochararray() Converts this string to a new character array. 40 String tolowercase() Converts all of the characters in this String to lower case using the rules of the default locale. 41 String tolowercase(locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale.

92 42 String tostring() This object (which is already a string!) is itself returned. 43 String touppercase() Converts all of the characters in this String to upper case using the rules of the default locale. 44 String touppercase(locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale. 45 String trim() Returns a copy of the string, with leading and trailing whitespace omitted. 46 static String valueof(primitive data type x) Returns the string representation of the passed data type argument. Java - Arrays Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1,..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and..., numbers[99] to represent individual variables.

93 This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. Declaring Array Variables: To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable: datatype[] arrayrefvar; // preferred way. or datatype arrayrefvar[]; // works but not preferred way. Note: The style datatype[] arrayrefvar is preferred. The style datatype arrayrefvar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. Example: The following code snippets are examples of this syntax: double[] mylist; // preferred way. or double mylist[]; // works but not preferred way. Creating Arrays: You can create an array by using the new operator with the following syntax: arrayrefvar = new datatype[arraysize]; The above statement does two things: It creates an array using new datatype[arraysize]; It assigns the reference of the newly created array to the variable arrayrefvar. Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:

94 datatype[] arrayrefvar = new datatype[arraysize]; Alternatively you can create arrays as follows: datatype[] arrayrefvar = {value0, value1,..., valuek; The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayrefvar.length-1. Example: Following statement declares an array variable, mylist, creates an array of 10 elements of double type and assigns its reference to mylist: double[] mylist = new double[10]; Following picture represents array mylist. Here, mylist holds ten double values and the indices are from 0 to 9.

95 Processing Arrays: When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. Example: Here is a complete example of showing how to create, initialize and process arrays: public class TestArray { public static void main(string[] args) { double[] mylist = {1.9, 2.9, 3.4, 3.5; // Print all the array elements for (int i = 0; i < mylist.length; i++) { System.out.println(myList[i] + " "); // Summing all elements double total = 0; for (int i = 0; i < mylist.length; i++) { total += mylist[i]; System.out.println("Total is " + total); // Finding the largest element double max = mylist[0]; for (int i = 1; i < mylist.length; i++) { if (mylist[i] > max) max = mylist[i]; System.out.println("Max is " + max); This would produce the following result:

96 3.5 Total is 11.7 Max is 3.5 The foreach Loops: JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. Example: The following code displays all the elements in the array mylist: public class TestArray { public static void main(string[] args) { double[] mylist = {1.9, 2.9, 3.4, 3.5; // Print all the array elements for (double element: mylist) { System.out.println(element); This would produce the following result: Passing Arrays to Methods: Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array: public static void printarray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " ");

97 You can invoke it by passing an array. For example, the following statement invokes the printarray method to display 3, 1, 2, 6, 4, and 2: printarray(new int[]{3, 1, 2, 6, 4, 2); Returning an Array from a Method: A method may also return an array. For example, the method shown below returns an array that is the reversal of another array: public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; return result; The Arrays Class: The java.util.arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types. SN Methods with Description 1 public static int binarysearch(object[] a, Object key) Searches the specified array of Object ( Byte, Int, double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1).

98 2 public static boolean equals(long[] a, long[] a2) Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.) 3 public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other primitive data types (Byte, short, Int etc.) 4 public static void sort(object[] a) Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other primitive data types ( Byte, short, Int, etc.) Java - Date & Time Java provides the Date class available in java.util package, this class encapsulates the current date and time. The Date class supports two constructors. The first constructor initializes the object with the current date and time. Date( ) The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970 Date(long millisec) Once you have a Date object available, you can call any of the following support methods to play with dates:

99 SN Methods with Description 1 boolean after(date date) Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false. 2 boolean before(date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false. 3 Object clone( ) Duplicates the invoking Date object. 4 int compareto(date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. 5 int compareto(object obj) Operates identically to compareto(date) if obj is of class Date. Otherwise, it throws a ClassCastException. 6 boolean equals(object date) Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false. 7 long gettime( ) Returns the number of milliseconds that have elapsed since January 1, 1970.

100 8 int hashcode( ) Returns a hash code for the invoking object. 9 void settime(long time) Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, String tostring( ) Converts the invoking Date object into a string and returns the result. Getting Current Date & Time This is very easy to get current date and time in Java. You can use a simple Date object with tostring() method to print current date and time as follows: import java.util.date; public class DateDemo { public static void main(string args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using tostring() System.out.println(date.toString()); This would produce the following result: Mon May 04 09:51:52 CDT 2009 Date Comparison:

101 There are following three ways to compare two dates: You can use gettime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. You can use the compareto( ) method, which is defined by the Comparable interface and implemented by Date. Date Formatting using SimpleDateFormat: SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For example: import java.util.*; import java.text.*; public class DateDemo { public static void main(string args[]) { Date dnow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.mm.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: " + ft.format(dnow)); This would produce the following result:

102 Current Date: Sun at 04:14:09 PM PDT Simple DateFormat format codes: To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following: Character Description Example G Era designator AD y Year in four digits 2001 M Month in year July or 07 d Day in month 10 h Hour in A.M./P.M. (1~12) 12 H Hour in day (0~23) 22 m Minute in hour 30 s Second in minute 55 S Millisecond 234 E Day in week Tuesday D Day in year 360 F Day of week in month 2 (second Wed. in July)

103 w Week in year 40 W Week in month 1 a A.M./P.M. marker PM k Hour in day (1~24) 24 K Hour in A.M./P.M. (0~11) 10 z Time zone Eastern Standard Time ' Escape for text Delimiter " Single quote ` UNIT II (7 Lectures) Constructor Handling: Constructors, Types of Constructors, Constructor Overloading, garbage collection, understand static, final, Polymorphism (overloading, overriding). Inheritance: Inheritance basics, using super, abstract and this keyword, using final with inheritance. Java - Methods A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console. Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.

104 Creating Method: Considering the following example to explain the syntax of a method: public static int funcname(int a, int b) { // body Here, public static : modifier. int: return type funcname: function name a, b: formal parameters

105 int a, int b: list of parameters Methods are also known as Procedures or Functions: Procedures: They don't return any value. Functions: They return value. Method definition consists of a method header and a method body. The same is shown below: modifier returntype nameofmethod (Parameter List) { // method body The syntax shown above includes: modifier: It defines the access type of the method and it is optional to use. returntype: Method may return a value. nameofmethod: This is the method name. The method signature consists of the method name and the parameter list. Parameter List: The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters. method body: The method body defines what the method does with statements. Example: Here is the source code of the above defined method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two: /** the snippet returns the minimum between two numbers */ public static int minfunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1;

106 return min; Method Calling: For using a method, it should be called. There are two ways in which a method is called i.e. method returns a value or returning nothing (no return value). The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when: return statement is executed. reaches the method ending closing brace. The methods returning void is considered as call to a statement. Lets consider an example: System.out.println("This is tutorialspoint.com!"); The method returning value can be understood by the following example: int result = sum(6, 9); Example: Following is the example to demonstrate how to define a method and how to call it: public class ExampleMinNumber{ public static void main(string[] args) { int a = 11; int b = 6; int c = minfunction(a, b); System.out.println("Minimum Value = " + c);

107 /** returns the minimum of two numbers */ public static int minfunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; This would produce the following result: Minimum value = 6 The void Keyword: The void keyword allows us to create methods which do not return a value. Here, in the following example we're considering a void methodmethodrankpoints. This method is a void method which does not return any value. Call to a void method must be a statement i.e.methodrankpoints(255.7);. It is a Java statement which ends with a semicolon as shown below. Example: public class ExampleVoid { public static void main(string[] args) { methodrankpoints(255.7); public static void methodrankpoints(double points) { if (points >= 202.5) { System.out.println("Rank:A1");

108 else if (points >= 122.4) { System.out.println("Rank:A2"); else { System.out.println("Rank:A3"); This would produce the following result: Rank:A1 Passing Parameters by Value: While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference. Passing Parameters by Value means calling a method with a parameter. Through this the argument value is passed to the parameter. Example: The following program shows an example of passing parameter by value. The values of the arguments remains the same even after the method invocation. public class swappingexample { public static void main(string[] args) { int a = 30; int b = 45; System.out.println("Before swapping, a = " + a + " and b = " + b);

109 // Invoke the swap method swapfunction(a, b); System.out.println("\n**Now, Before and After swapping values will be same here**:"); System.out.println("After swapping, a = " + a + " and b is " + b); public static void swapfunction(int a, int b) { System.out.println("Before swapping(inside), a = " + a + " b = " + b); // Swap n1 with n2 int c = a; a = b; b = c; System.out.println("After swapping(inside), a = " + a + " b = " + b); This would produce the following result: Before swapping, a = 30 and b = 45 Before swapping(inside), a = 30 b = 45 After swapping(inside), a = 45 b = 30 **Now, Before and After swapping values will be same here**: After swapping, a = 30 and b is 45

110 Java - Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed. The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object. A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type. Example: Let us look at an example. public interface Vegetarian{ public class Animal{ public class Deer extends Animal implements Vegetarian{ Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example: A Deer IS-A Animal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object

111 When we apply the reference variable facts to a Deer object reference, the following declarations are legal: Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d; All the reference variables d,a,v,o refer to the same Deer object in the heap. Virtual Methods: In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes. We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method. /* File name : Employee.java */ public class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; public void mailcheck() { System.out.println("Mailing a check to " + this.name + " " + this.address);

112 public String tostring() { return name + " " + address + " " + number; public String getname() { return name; public String getaddress() { return address; public void setaddress(string newaddress) { address = newaddress; public int getnumber() { return number; Now suppose we extend Employee class as follows: /* File name : Salary.java */ public class Salary extends Employee { private double salary; //Annual salary public Salary(String name, String address, int number, double salary) { super(name, address, number); setsalary(salary);

113

114 public void mailcheck() { System.out.println("Within mailcheck of Salary class "); System.out.println("Mailing check to " + getname() + " with salary " + salary); public double getsalary() { return salary; public void setsalary(double newsalary) { if(newsalary >= 0.0) { salary = newsalary; public double computepay() { System.out.println("Computing salary pay for " + getname()); return salary/52; Now, you study the following program carefully and try to determine its output: /* File name : VirtualDemo.java */ public class VirtualDemo { public static void main(string [] args) { Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, ); Employee e = new Salary("John Adams", "Boston, MA", 2, );

115 System.out.println("Call mailcheck using Salary reference --"); s.mailcheck(); System.out.println("\n Call mailcheck using Employee reference--"); e.mailcheck(); This would produce the following result: Constructing an Employee Constructing an Employee Call mailcheck using Salary reference -- Within mailcheck of Salary class Mailing check to Mohd Mohtashim with salary Call mailcheck using Employee reference-- Within mailcheck of Salary class Mailing check to John Adams with salary Here, we instantiate two Salary objects. one using a Salary reference s, and the other using an Employee reference e. While invoking S.MAILCHECK() the compiler sees mailcheck() in the Salary class at compile time, and the JVM invokes mailcheck() in the Salary class at run time. Invoking mailcheck() on e is quite different because e is an Employee reference. When the compiler sees E.MAILCHECK(), the compiler sees the mailcheck() method in the Employee class. Here, at compile time, the compiler used mailcheck() in Employee to validate this statement. At run time, however, the JVM invokes mailcheck() in the Salary class. This behavior is referred to as virtual method invocation, and the methods are referred to as virtual methods. All methods in Java behave in this manner, whereby an overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.

116 Method Overloading: When a class has two or more methods by same name but different parameters, it is known as method overloading. It is different from overriding. In overriding a method has same method name, type, number of parameters etc. Lets consider the example shown before for finding minimum numbers of integer type. If, lets say we want to find minimum number of double type. Then the concept of Overloading will be introduced to create two or more methods with the same name but different parameters. The below example explains the same: public class ExampleOverloading{ public static void main(string[] args) { int a = 11; int b = 6; double c = 7.3; double d = 9.4; int result1 = minfunction(a, b); // same function name with different parameters double result2 = minfunction(c, d); System.out.println("Minimum Value = " + result1); System.out.println("Minimum Value = " + result2); // for integer public static int minfunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min;

117 // for double public static double minfunction(double n1, double n2) { double min; if (n1 > n2) min = n2; else min = n1; return min; This would produce the following result: Minimum Value = 6 Minimum Value = 7.3 Overloading methods makes program readable. Here, two methods are given same name but with different parameters. The minimum number from integer and double types is the result. Using Command-Line Arguments: Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy.they are stored as strings in the String array passed to main( ). Example: The following program displays all of the command-line arguments that it is called with: public class CommandLine { public static void main(string args[]){ for(int i=0; i<args.length; i++){

118 System.out.println("args[" + i + "]: " + args[i]); Try executing this program as shown here: java CommandLine this is a command line This would produce the following result: args[0]: this args[1]: is args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: -100 The Constructors: Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object. All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.

119 Rules for creating java constructor There are basically two rules defined for the constructor. 4. Constructor name must be same as its class name 5. Constructor must have no explicit return type Example: Here is a simple example that uses a constructor: // A simple constructor. class MyClass { int x; // Following is the constructor MyClass() { x = 10; You would call constructor to initialize objects as follows: public class ConsDemo { public static void main(string args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(); System.out.println(t1.x + " " + t2.x); Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor's name.

120 Example: Here is a simple example that uses a constructor: // A simple constructor. class MyClass { int x; // Following is the constructor MyClass(int i ) { x = i; You would call constructor to initialize objects as follows: public class ConsDemo { public static void main(string args[]) { MyClass t1 = new MyClass( 10 ); MyClass t2 = new MyClass( 20 ); System.out.println(t1.x + " " + t2.x); This would produce the following result: Types of java constructors There are two types of constructors: 7. Default constructor (no-arg constructor) 8. Parameterized constructor

121 Java Default Constructor Constructors that have no parameter is known as default constructor. Syntax of default constructor: <class_name>(){ Example of default constructor In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. 3. class Bike1 4. { 5. Bike1() 6. { 7. System.out.println("Bike is created"); public static void main(string args[]) 10. { 11. Bike1 b=new Bike1(); Test it Now Output: Bike is created Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

122 Q) What is the purpose of default constructor? 10. Default constructor provides the default values to the object like 0, null etc. depending on the type. Example of default constructor that displays the default values class Student3 { int id; String name; void display() { System.out.println(id+" "+name); public static void main(string args[]) { Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); Test it Now Output: 8. null 9. null Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.here 0 and null values are provided by default constructor.

123 Java parameterized constructor A constructor that have parameters is known as parameterized constructor. Why use parameterized constructor? Parameterized constructor is used to provide different values to the distinct objects. Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. class Student4 { int id; String name; 6. Student4(int i,string n) 7. { 8. id = i; 9. name = n; void display(){system.out.println(id+" "+name); public static void main(string args[]){ 14. Student4 s1 = new Student4(111,"Karan"); 15. Student4 s2 = new Student4(222,"Aryan"); 16. s1.display(); 17. s2.display(); Test it Now Output: 111 Karan 222 Aryan Constructor Overloading in Java Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.the compiler differentiates these constructors by

124 taking into account the number of parameters in the list and their type. Example of Constructor Overloading 1. class Student5 2. { 3. int id; 4. String name; 5. int age; 6. Student5(int i,string n) 7. { 8. id = i; 9. name = n; Student5(int i,string n,int a) 12. { 13. id = i; 14. name = n; 15. age=a; void display(){system.out.println(id+" "+name+" "+age); public static void main(string args[]){ 20. Student5 s1 = new Student5(111,"Karan"); 21. Student5 s2 = new Student5(222,"Aryan",25); 22. s1.display(); 23. s2.display(); Test it Now Output: 111 Karan Aryan 25 Difference between constructor and method in java There are many differences between constructors and methods. They are given below. Java Constructor Java Method Constructor is used to initialize the state of an Method is used to expose

125 object. behaviour of an object. Constructor must not have return type. Method must have return type. Constructor is invoked implicitly. Method is invoked explicitly. The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case. Constructor name must be same as the class name. Method name may or may not be same as class name. Java Copy Constructor There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in java. They are: By constructor By assigning the values of one object into another By clone() method of Object class In this example, we are going to copy the values of one object into another using java constructor. 1. class Student6{ 2. int id; 3. String name; 4. Student6(int i,string n){ 5. id = i; 6. name = n; Student6(Student6 s){ 10. id = s.id; 11. name =s.name; void display(){system.out.println(id+" "+name); 14.

126 15. public static void main(string args[]){ 16. Student6 s1 = new Student6(111,"Karan"); 17. Student6 s2 = new Student6(s1); 18. s1.display(); 19. s2.display(); Test it Now Output: 111 Karan 111 Karan Copying values without constructor We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor. class Student7{ int id; String name; Student7(int i,string n){ id = i; name = n; Student7(){ void display(){system.out.println(id+" "+name); public static void main(string args[]){ Student7 s1 = new Student7(111,"Karan"); Student7 s2 = new Student7(); s2.id=s1.id; s2.name=s1.name; s1.display(); s2.display(); Test it Now Output: 111 Karan 111 Karan

127 Q) Does constructor return any value? Ans:yes, that is current class instance (You cannot use return type yet it returns a value). Can constructor perform other tasks instead of initialization? Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method. Variable Arguments(var-args): JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows: typename... parametername In the method declaration, you specify the type followed by an ellipsis (...) Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it. Example: public class VarargsDemo { public static void main(string args[]) { // Call method with variable args printmax(34, 3, 3, 2, 56.5); printmax(new double[]{1, 2, 3); public static void printmax( double... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; double result = numbers[0];

128 for (int i = 1; i < numbers.length; i++) if (numbers[i] > result) result = numbers[i]; System.out.println("The max value is " + result); This would produce the following result: The max value is 56.5 The max value is 3.0 The finalize( ) Method: It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly. For example, you might use finalize( ) to make sure that an open file owned by that object is closed. To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed. The finalize( ) method has this general form: protected void finalize( ) { // finalization code here Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.

129 Method Overloading in Java If a class have multiple methods by same name but different parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behaviour of the method because its name differs. So, we perform method overloading to figure out the program quickly. Advantage of method overloading? Method overloading increases the readability of the program. Different ways to overload the method There are two ways to overload the method in java By changing number of arguments By changing the data type In java, Methood Overloading is not possible by changing the return type of the method. 1)Example of Method Overloading by changing the no. of arguments In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers. 4. class Calculation{ 5. void sum(int a,int b){system.out.println(a+b); 6. void sum(int a,int b,int c){system.out.println(a+b+c); 7. public static void main(string args[]){

130 Calculation obj=new Calculation(); obj.sum(10,10,10); obj.sum(20,20); 9. 4) 5) Test it Now Output: )Example of Method Overloading by changing data type of argument In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments. class Calculation2{ void sum(int a,int b){system.out.println(a+b); void sum(double a,double b){system.out.println(a+b); 5. public static void main(string args[]){ 6. Calculation2 obj=new Calculation2(); 7. obj.sum(10.5,10.5); 8. obj.sum(20,20); Test it Now Output: Que) Why Method Overloaing is not possible by changing the return type of method? In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur: because there was problem:

131 1. class Calculation3{ 2. int sum(int a,int b){system.out.println(a+b); 3. double sum(int a,int b){system.out.println(a+b); public static void main(string args[]){ 6. Calculation3 obj=new Calculation3(); 7. int result=obj.sum(20,20); //Compile Time Error Test it Now int result=obj.sum(20,20); //Here how can java determine which sum() method should be called Can we overload main() method? Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example: 1. class Overloading1{ 2. public static void main(int a){ 3. System.out.println(a); public static void main(string args[]){ 7. System.out.println("main() method invoked"); 8. main(10); Test it Now Output:main() method invoked 10 Method Overloading and TypePromotion One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by the figure given below:

132 As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float or double and so on. Example of Method Overloading with TypePromotion 1. class OverloadingCalculation1{ 2. void sum(int a,long b){system.out.println(a+b); 3. void sum(int a,int b,int c){system.out.println(a+b+c); public static void main(string args[]){ 6. OverloadingCalculation1 obj=new OverloadingCalculation1(); 7. obj.sum(20,20);//now second int literal will be promoted to long 8. obj.sum(20,20,20); Test it Now Output:40

133 60 Example of Method Overloading with TypePromotion if matching found If there are matching type arguments in the method, type promotion is not performed. 1. class OverloadingCalculation2{ 2. void sum(int a,int b){system.out.println("int arg method invoked"); 3. void sum(long a,long b){system.out.println("long arg method invoked"); public static void main(string args[]){ 6. OverloadingCalculation2 obj=new OverloadingCalculation2(); 7. obj.sum(20,20);//now int arg sum() method gets invoked Test it Now Output:int arg method invoked Example of Method Overloading with TypePromotion in case ambiguity If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity. 1. class OverloadingCalculation3{ 2. void sum(int a,long b){system.out.println("a method invoked"); 3. void sum(long a,int b){system.out.println("b method invoked"); public static void main(string args[]){ 6. OverloadingCalculation3 obj=new OverloadingCalculation3(); 7. obj.sum(20,20);//now ambiguity Test it Now Output:Compile Time Error

134 One type is not de-promoted implicitly for example double cannot be depromoted to any type implicitely. Java static keyword 1. Static variable 2. Program of counter without static variable 3. Program of counter with static variable 4. Static method 5. Restrictions for static method 6. Why main method is static? 7. Static block 8. Can we execute a program without main method? The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. The static can be: 1. variable (also known as class variable) 2. method (also known as class method) 3. block 4. nested class Java static variable If you declare any variable as static, it is known static variable. The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. The static variable gets memory only once in class area at the time of class loading. Advantage of static variable It makes your program memory efficient (i.e it saves memory). Understanding problem without static variable 1. class Student{

135 2. int rollno; 3. String name; 4. String college="its"; 5. Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.all student have its unique rollno and name so instance data member is good.here, college refers to the common property of all objects.if we make it static,this field will get memory only once. Java static property is shared to all objects. Example of static variable 1. //Program of static variable class Student8{ 4. int rollno; 5. String name; 6. static String college ="ITS"; Student8(int r,string n){ 9. rollno = r; 10. name = n; void display (){System.out.println(rollno+" "+name+" "+college); public static void main(string args[]){ 15. Student8 s1 = new Student8(111,"Karan"); 16. Student8 s2 = new Student8(222,"Aryan"); s1.display(); 19. s2.display(); Test it Now Output:111 Karan ITS 222 Aryan ITS

136 Program of counter without static variable In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable. 1. class Counter{ 2. int count=0;//will get memory when instance is created Counter(){ 5. count++; 6. System.out.println(count); public static void main(string args[]){ Counter c1=new Counter(); 12. Counter c2=new Counter();

137 13. Counter c3=new Counter(); Test it Now Output:1 1 1 Program of counter by static variable As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value. 1. class Counter2{ 2. static int count=0;//will get memory only once and retain its value Counter2(){ 5. count++; 6. System.out.println(count); public static void main(string args[]){ Counter2 c1=new Counter2(); 12. Counter2 c2=new Counter2(); 13. Counter2 c3=new Counter2(); Test it Now Output: ) Java static method If you apply static keyword with any method, it is known as static method. o o o A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.

138 Example of static method 1. //Program of changing the common property of all objects(static field) class Student9{ 4. int rollno; 5. String name; 6. static String college = "ITS"; static void change(){ 9. college = "BBDIT"; Student9(int r, String n){ 13. rollno = r; 14. name = n; void display (){System.out.println(rollno+" "+name+" "+college); public static void main(string args[]){ 20. Student9.change(); Student9 s1 = new Student9 (111,"Karan"); 23. Student9 s2 = new Student9 (222,"Aryan"); 24. Student9 s3 = new Student9 (333,"Sonoo"); s1.display(); 27. s2.display(); 28. s3.display(); Test it Now Output:111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT Another example of static method that performs normal calculation 1. //Program to get cube of a given number by static method class Calculate{ 4. static int cube(int x){ 5. return x*x*x; public static void main(string args[]){

139 9. int result=calculate.cube(5); 10. System.out.println(result); Test it Now Output:125 Restrictions for static method There are two main restrictions for the static method. They are: 1. The static method can not use non static data member or call non-static method directly. 2. this and super cannot be used in static context. 1. class A{ 2. int a=40;//non static 3. public static void main(string args[]){ System.out.println(a); Test it Now Output:Compile Time Error Q) why java main method is static? Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation. 3) Java static block // Is used to initialize the static data member. // It is executed before main method at the time of classloading. Example of static block // class A2{ // static{system.out.println("static block is invoked"); // public static void main(string args[]){ // System.out.println("Hello main"); // // Test it Now

140 Output:static block is invoked Hello main Q) Can we execute a program without main() method? Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7. class A3{ static{ System.out.println("static block is invoked"); System.exit(0); Test it Now Output:static block is invoked (if not JDK7) In JDK7 and above, output will be: Output:Error: Main method not found in class A3, please define the main method as: public static void main(string[] args) this keyword in java // this keyword // Usage of this keyword // to refer the current class instance variable // to invoke the current class constructor // to invoke the current class method // to pass as an argument in the method call // to pass as an argument in the constructor call // to return the current class instance 3. Proving this keyword There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Usage of java this keyword Here is given the 6 usage of java this keyword.

141 this keyword can be used to refer current class instance variable. this() can be used to invoke current class constructor. this keyword can be used to invoke current class method (implicitly) this can be passed as an argument in the method call. this can be passed as argument in the constructor call. this keyword can also be used to return the current class instance. Suggestion: If you are beginner to java, lookup only two usage of this keyword. 1) The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity. Understanding the problem without this keyword Let's understand the problem if we don't use this keyword by the example given below: 1. class Student10{ 2. int id; 3. String name; Student10(int id,string name){ 6. id = id; 7. name = name; void display(){system.out.println(id+" "+name); public static void main(string args[]){ 12. Student10 s1 = new Student10(111,"Karan"); 13. Student10 s2 = new Student10(321,"Aryan"); 14. s1.display(); 15. s2.display();

142 Test it Now Output:0 null 0 null In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable. Solution of the above problem by this keyword 1. //example of this keyword 2. class Student11{ 3. int id; 4. String name; Student11(int id,string name){ 7. this.id = id; 8. this.name = name; void display(){system.out.println(id+" "+name); 11. public static void main(string args[]){ 12. Student11 s1 = new Student11(111,"Karan"); 13. Student11 s2 = new Student11(222,"Aryan"); 14. s1.display(); 15. s2.display(); Test it Now Output111 Karan 222 Aryan

143 If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program: Program where this keyword is not required 1. class Student12{ 2. int id; 3. String name; Student12(int i,string n){ 6. id = i; 7. name = n; void display(){system.out.println(id+" "+name); 10. public static void main(string args[]){ 11. Student12 e1 = new Student12(111,"karan"); 12. Student12 e2 = new Student12(222,"Aryan"); 13. e1.display(); 14. e2.display(); Test it Now Output:111 Karan

144 222 Aryan 2) this() can be used to invoked current class constructor. The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor. 1. //Program of this() constructor call (constructor chaining) class Student13{ 4. int id; 5. String name; 6. Student13(){System.out.println("default constructor is invoked"); Student13(int id,string name){ 9. this ();//it is used to invoked current class constructor. 10. this.id = id; 11. this.name = name; void display(){system.out.println(id+" "+name); public static void main(string args[]){ 16. Student13 e1 = new Student13(111,"karan"); 17. Student13 e2 = new Student13(222,"Aryan"); 18. e1.display(); 19. e2.display(); Test it Now Output: default constructor is invoked default constructor is invoked 111 Karan 222 Aryan Where to use this() constructor call? The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword. 1. class Student14{ 2. int id; 3. String name;

145 4. String city; Student14(int id,string name){ 7. this.id = id; 8. this.name = name; Student14(int id,string name,string city){ 11. this(id,name);//now no need to initialize id and name 12. this.city=city; void display(){system.out.println(id+" "+name+" "+city); public static void main(string args[]){ 17. Student14 e1 = new Student14(111,"karan"); 18. Student14 e2 = new Student14(222,"Aryan","delhi"); 19. e1.display(); 20. e2.display(); Test it Now Output:111 Karan null 222 Aryan delhi Rule: Call to this() must be the first statement in constructor. 1. class Student15{ 2. int id; 3. String name; 4. Student15(){System.out.println("default constructor is invoked"); Student15(int id,string name){ 7. id = id; 8. name = name; 9. this ();//must be the first statement void display(){system.out.println(id+" "+name); public static void main(string args[]){ 14. Student15 e1 = new Student15(111,"karan"); 15. Student15 e2 = new Student15(222,"Aryan"); 16. e1.display(); 17. e2.display(); Test it Now Output:Compile Time Error

146 3)The this keyword can be used to invoke current class method (implicitly). You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example 1. class S{ 2. void m(){ 3. System.out.println("method is invoked"); void n(){ 6. this.m();//no need because compiler does it for you void p(){ 9. n();//complier will add this to invoke n() method as this.n() public static void main(string args[]){ 12. S s1 = new S(); 13. s1.p(); Test it Now Output:method is invoked 4) this keyword can be passed as an argument in the method. The this keyword can also be passed as an argument in the method. It is mainly used in

147 the event handling. Let's see the example: 1. class S2{ 2. void m(s2 obj){ 3. System.out.println("method is invoked"); void p(){ 6. m(this); public static void main(string args[]){ 10. S2 s1 = new S2(); 11. s1.p(); Test it Now Output:method is invoked Application of this that can be passed as an argument: In event handling (or) in a situation where we have to provide reference of a class to another one. 5) The this keyword can be passed as argument in the constructor call. We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example: 1. class B{ 2. A4 obj; 3. B(A4 obj){ 4. this.obj=obj; void display(){ 7. System.out.println(obj.data);//using data member of A4 class class A4{ 12. int data=10; 13. A4(){ 14. B b=new B(this); 15. b.display(); public static void main(string args[]){ 18. A4 a=new A4();

148 Test it Now Output:10 6) The this keyword can be used to return current class instance. We can return the this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example: Syntax of this that can be returned as a statement 1. return_type method_name(){ 2. return this; 3. Example of this keyword that you return as a statement from the method 1. class A{ 2. A geta(){ 3. return this; void msg(){system.out.println("hello java"); class Test1{ 9. public static void main(string args[]){ 10. new A().getA().msg(); Test it Now Output:Hello java Proving this keyword Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same. 1. class A5{ 2. void m(){ 3. System.out.println(this);//prints same reference ID public static void main(string args[]){

149 7. A5 obj=new A5(); 8. System.out.println(obj);//prints the reference ID obj.m(); Test it Now Java - Abstraction Advertisements Previous Page Next Page Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class. If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own. Abstract Class: Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword. /* File name : Employee.java */ public abstract class Employee {

150 private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; public double computepay() { System.out.println("Inside Employee computepay"); return 0.0; public void mailcheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); public String tostring() { return name + " " + address + " " + number; public String getname() { return name; public String getaddress() { return address; public void setaddress(string newaddress)

151 { address = newaddress; public int getnumber() { return number; Notice that nothing is different in this Employee class. The class is now abstract, but it still has three fields, seven methods, and one constructor. Now if you would try as follows: /* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(string [] args) { /* Following is not allowed and would raise error */ Employee e = new Employee("George W.", "Houston, TX", 43); System.out.println("\n Call mailcheck using Employee reference-- "); e.mailcheck(); When you would compile above class then you would get the following error: Employee.java:46: Employee is abstract; cannot be instantiated Employee e = new Employee("George W.", "Houston, TX", 43); ^ 1 error

152 Extending Abstract Class: We can extend Employee class in normal way as follows: /* File name : Salary.java */ public class Salary extends Employee { private double salary; //Annual salary public Salary(String name, String address, int number, double salary) { super(name, address, number); setsalary(salary); public void mailcheck() { System.out.println("Within mailcheck of Salary class "); System.out.println("Mailing check to " + getname() + " with salary " + salary); public double getsalary() { return salary; public void setsalary(double newsalary) { if(newsalary >= 0.0) { salary = newsalary; public double computepay() { System.out.println("Computing salary pay for " + getname());

153 return salary/52; Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary object will inherit the three fields and seven methods from Employee. /* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(string [] args) { Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, ); Employee e = new Salary("John Adams", "Boston, MA", 2, ); System.out.println("Call mailcheck using Salary reference --"); s.mailcheck(); System.out.println("\n Call mailcheck using Employee reference-- "); e.mailcheck(); This would produce the following result: Constructing an Employee Constructing an Employee Call mailcheck using Salary reference -- Within mailcheck of Salary class Mailing check to Mohd Mohtashim with salary Call mailcheck using Employee reference-- Within mailcheck of Salary class Mailing check to John Adams with salary 2400.

154 Abstract Methods: If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract. The abstract keyword is also used to declare a method as abstract. An abstract method consists of a method signature, but no method body. Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows: public abstract class Employee { private String name; private String address; private int number; public abstract double computepay(); //Remainder of class definition Declaring a method as abstract has two results: The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well. Any child class must either override the abstract method or declare itself abstract. A child class that inherits an abstract method must override it. If they do not, they must be abstract and any of their children must override it. Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated. If Salary is extending Employee class, then it is required to implement computepay() method as follows:

155 /* File name : Salary.java */ public class Salary extends Employee { private double salary; // Annual salary public double computepay() { System.out.println("Computing salary pay for " + getname()); return salary/52; //Remainder of class definition Java - Encapsulation Advertisements Previous Page Next Page Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

156 The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code. Example: Let us look at an example that depicts encapsulation: /* File name : EncapTest.java */ public class EncapTest{ private String name; private String idnum; private int age; public int getage(){ return age; public String getname(){ return name; public String getidnum(){ return idnum; public void setage( int newage){ age = newage; public void setname(string newname){ name = newname;

157 public void setidnum( String newid){ idnum = newid; The public methods are the access points to this class' fields from the outside java world. Normally, these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters. The variables of the EncapTest class can be access as below:: /* File name : RunEncap.java */ public class RunEncap{ public static void main(string args[]){ EncapTest encap = new EncapTest(); encap.setname("james"); encap.setage(20); encap.setidnum("12343ms"); System.out.print("Name : " + encap.getname()+ " Age : "+ encap.getage()); This would produce the following result: Name : James Age : 20 Benefits of Encapsulation: The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.

158 Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. When we talk about inheritance, the most commonly used keyword would be extends and implements. Inheritance represents the IS-A relationship, also known as parent-child relationship. IS-A Relationship: IS-A is a way of saying : This object is a type of that object. Let us see how theextends keyword is used to achieve inheritance. public class Animal{ public class Mammal extends Animal{ public class Reptile extends Animal{ public class Dog extends Mammal{ Now, based on the above example, In Object Oriented terms, the following are true: Animal is the superclass of Mammal class. Animal is the superclass of Reptile class. Mammal and Reptile are subclasses of Animal class.

159 Dog is the subclass of both Mammal and Animal classes. Now, if we consider the IS-A relationship, we can say: Mammal IS-A Animal Reptile IS-A Animal Dog IS-A Mammal Hence : Dog IS-A Animal as well With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass. We can assure that Mammal is actually an Animal with the use of the instance operator. Example: public class Dog extends Mammal{ public static void main(string args[]){ Animal a = new Animal(); Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); This would produce the following result: true true true

160 Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship. The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes. Example: public interface Animal { public class Mammal implements Animal{ public class Dog extends Mammal{ The instanceof Keyword: Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal interface Animal{ class Mammal implements Animal{ public class Dog extends Mammal{ public static void main(string args[]){ Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal);

161 This would produce the following result: true true true HAS-A relationship: These relationships are mainly based on the usage. This determines whether a certain class HAS- A certain thing. This relationship helps to reduce duplication of code as well as bugs. Lets us look into an example: public class Vehicle{ public class Speed{ public class Van extends Vehicle{ private Speed sp; This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications. In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action. A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal: public class extends Animal, Mammal{ However, a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance. Why use inheritance in java For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

162 Syntax of Java Inheritance 1. class Subclass-name extends Superclass-name 2. { 3. //methods and fields 4. The extends keyword indicates that you are making a new class that derives from an existing class. In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass. Understanding the simple example of inheritance As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee. 1. class Employee{ 2. float salary=40000; class Programmer extends Employee{ 5. int bonus=10000;

163 6. public static void main(string args[]){ 7. Programmer p=new Programmer(); 8. System.out.println("Programmer salary is:"+p.salary); 9. System.out.println("Bonus of Programmer is:"+p.bonus); Test it Now Programmer salary is: Bonus of programmer is:10000 In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

164 Note: Multiple inheritance is not supported in java through class. When a class extends multiple classes i.e. known as multiple inheritance. For Example:

165 Q) Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class. Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now. 1. class A{ 2. void msg(){system.out.println("hello"); class B{ 5. void msg(){system.out.println("welcome"); 6.

166 7. class C extends A,B{//suppose if it were Public Static void main(string args[]){ 10. C obj=new C(); 11. obj.msg();//now which msg() method would be invoked? Test it Now Compile Time Error Aggregation in Java If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS- A relationship. Consider a situation, Employee object contains many informations such as id, name, id etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below. 1. class Employee{ 2. int id; 3. String name; 4. Address address;//address is a class In such case, Employee has an entity reference address, so relationship is Employee HAS-A address. Why use Aggregation? For Code Reusability. Simple Example of Aggregation

167 In this example, we have created the reference of Operation class in the Circle class. 1. class Operation{ 2. int square(int n){ 3. return n*n; class Circle{ 8. Operation op;//aggregation 9. double pi=3.14; double area(int radius){ 12. op=new Operation(); 13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call). 14. return pi*rsquare; public static void main(string args[]){ 20. Circle c=new Circle(); 21. double result=c.area(5); 22. System.out.println(result); Test it Now Output:78.5 When use Aggregation? Code reuse is also best achieved by aggregation when there is no is-a relationship. Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice. Understanding meaningful example of Aggregation In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In such case relationship is Employee HAS-A address. Address.java 1. public class Address { 2. String city,state,country; public Address(String city, String state, String country) {

168 5. this.city = city; 6. this.state = state; 7. this.country = country; Emp.java 1. public class Emp { 2. int id; 3. String name; 4. Address address; public Emp(int id, String name,address address) { 7. this.id = id; 8. this.name = name; 9. this.address=address; void display(){ 13. System.out.println(id+" "+name); 14. System.out.println(address.city+" "+address.state+" "+address.country); public static void main(string[] args) { 18. Address address1=new Address("gzb","UP","india"); 19. Address address2=new Address("gno","UP","india"); Emp e=new Emp(111,"varun",address1); 22. Emp e2=new Emp(112,"arun",address2); e.display(); 25. e2.display(); Test it Now Output:111 varun gzb UP india 112 arun gno UP india download this example Method Overriding in Java

169 We know about super classes and sub classes. If a class inherits a method from its super class, then there is a chance to override the method provided that it is not marked final. The benefit of overriding is: ability to define a behavior that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement. In object-oriented terms, overriding means to override the functionality of an existing method. Example: Let us look at an example. class Animal{ public void move(){ System.out.println("Animals can move"); class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); public class TestDog{ public static void main(string args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//runs the method in Dog class

170 This would produce the following result: Animals can move Dogs can walk and run In the above example, you can see that the even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object. Consider the following example : class Animal{ public void move(){ System.out.println("Animals can move"); class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); public void bark(){ System.out.println("Dogs can bark"); public class TestDog{

171 public static void main(string args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//runs the method in Dog class b.bark(); This would produce the following result: TestDog.java:30: cannot find symbol symbol : method bark() location: class Animal b.bark(); ^ This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark. Rules for method overriding: The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overridding method in the sub class cannot be either private or protected. Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden.

172 A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected. An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. Constructors cannot be overridden. Using the super keyword: When invoking a superclass version of an overridden method the superkeyword is used. class Animal{ public void move(){ System.out.println("Animals can move"); class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); public class TestDog{ public static void main(string args[]){

173 Animal b = new Dog(); // Animal reference but Dog object b.move(); //Runs the method in Dog class This would produce the following result: Animals can move Dogs can walk and run If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. Usage of Java Method Overriding o o Method overriding is used to provide specific implementation of a method that is already provided by its super class. Method overriding is used for runtime polymorphism Rules for Java Method Overriding 1. method must have same name as in the parent class 2. method must have same parameter as in the parent class. 3. must be IS-A relationship (inheritance). Understanding the problem without method overriding Let's understand the problem that we may face in the program if we don't use method overriding. 1. class Vehicle{ 2. void run(){system.out.println("vehicle is running"); class Bike extends Vehicle{ public static void main(string args[]){ 7. Bike obj = new Bike();

174 8. obj.run(); Test it Now Output:Vehicle is running Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding. Example of method overriding In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding. 1. class Vehicle{ 2. void run(){system.out.println("vehicle is running"); class Bike2 extends Vehicle{ 5. void run(){system.out.println("bike is running safely"); public static void main(string args[]){ 8. Bike2 obj = new Bike2(); 9. obj.run(); 10. Test it Now Output:Bike is running safely Real example of Java Method Overriding Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.

175 1. class Bank{ 2. int getrateofinterest(){return 0; class SBI extends Bank{ 6. int getrateofinterest(){return 8; class ICICI extends Bank{ 10. int getrateofinterest(){return 7; class AXIS extends Bank{ 13. int getrateofinterest(){return 9; class Test2{ 17. public static void main(string args[]){ 18. SBI s=new SBI(); 19. ICICI i=new ICICI(); 20. AXIS a=new AXIS(); 21. System.out.println("SBI Rate of Interest: "+s.getrateofinterest()); 22. System.out.println("ICICI Rate of Interest: "+i.getrateofinterest()); 23. System.out.println("AXIS Rate of Interest: "+a.getrateofinterest()); Test it Now Output: SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9 Can we override static method?

176 No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later. Why we cannot override static method? because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area. Can we override java main method? No, because main is a static method. Difference between method overloading and method overriding in java There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below: No. Method Overloading Method Overriding 1) Method overloading is used to increase the Method overriding is used to readability of the program. provide the specific implementation of the method that is already provided by its super class. 2) Method overloading is performed within Method overriding occurs in two class. classes that have IS-A (inheritance) relationship. 3) In case of method overloading, parameter In case of method overriding,

177 must be different. parameter must be same. 4) Method overloading is the example of Method overriding is the compile time polymorphism. example of run time polymorphism. 5) In java, method overloading can't be Return type must be same or performed by changing return type of the covariant in method overriding. method only. Return type can be same or different in method overloading. But you must have to change the parameter. Java Method Overloading example copy to clipboard 1. class OverloadingExample{ 2. static int add(int a,int b){return a+b; 3. static int add(int a,int b,int c){return a+b+c; 4. class OverloadingExample{ static int add(int a,int b){return a static int add(int a,int b,int c){ret Java Method Overriding example copy to clipboard 1. class Animal{ 2. void eat(){system.out.println("eating..."); class Dog extends Animal{ 5. void eat(){system.out.println("eating bread..."); 6. UNIT IV

178 Threading & Networking (5 Lectures) Multithreaded programming- Multithreaded Programming: The Java thread model, the main thread, creating multiple threads, using Alive () and join (), thread priorities, synchronization, suspending, resuming, and stopping threads, using multithreading. Networking (datagram socket and TCP/IP based server socket), Multithreading in Java Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation etc. Java is a multithreaded programming language which means we can develop multithreaded program using Java. A multithreaded program contains two or more parts that can run concurrently and each part can handle different task at the same time making optimal use of the available resources especially when your computer has multiple CPUs. By definition multitasking is when multiple processes share common processing resources such as a CPU. Multithreading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multithreading enables you to write in a way where multiple activities can proceed concurrently in the same program.

179 Advantage of Java Multithreading 13. It doesn't block the user because threads are independent and you can perform multiple operations at same time. 14. You can perform many operations together so it saves time. 15. Threads are independent so it doesn't affect other threads if exception occur in a single thread. Multitasking Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: o Process-based Multitasking(Multiprocessing) Thread-based Multitasking(Multithreading) 1) Process-based Multitasking (Multiprocessing) o Each process have its own address in memory i.e. each process allocates separate memory area. o Process is heavyweight. o Cost of communication between the process is high. Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc. 2) Thread-based Multitasking (Multithreading) o Threads share the same address space. o Thread is lightweight. o Cost of communication between the thread is low. Note: At least one process is required for each thread.

180 What is Thread in java A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area. As shown in the above figure, thread is executed inside the process. There is contextswitching between the threads. There can be multiple processes inside the OS and one process can have multiple threads. Note: At a time one thread is executed only.

181 Life cycle of a Thread (Thread States) A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state. But for better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated

182 1) New The thread is in new state if you create an instance of Thread class but before the invocation of start() method. A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. 2) Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task 3) Running The thread is in running state if the thread scheduler has selected it. 4) Waiting/ Non-Runnable (Blocked) /Timed Waiting : Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.a thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.this is the state when the thread is still alive, but is currently not eligible to run. A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

183 5) Terminated A thread is in terminated or dead state when its run () method exits. A runnable thread enters the terminated state when it completes its task or otherwise terminates. Thread Priorities: Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). 3 constants defiend in Thread class: 1. public static int MIN_PRIORITY 2. public static int NORM_PRIORITY 3. public static int MAX_PRIORITY Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent. Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10. Example of priority of a Thread: 1. class TestMultiPriority1 extends Thread{ 2. public void run(){ 3. System.out.println("running thread name is:"+thread.currentthread().getname()); 4. System.out.println("running thread priority is:"+thread.currentthread().getpriority()); 5.

184 6. 7. public static void main(string args[]){ 8. TestMultiPriority1 m1=new TestMultiPriority1(); 9. TestMultiPriority1 m2=new TestMultiPriority1(); 10. m1.setpriority(thread.min_priority); 11. m2.setpriority(thread.max_priority); 12. m1.start(); 13. m2.start(); Test it Now Output:running thread name is:thread-0 running thread priority is:10 running thread name is:thread-1 running thread priority is:1 Example that creates a new thread and starts it running: class RunnableDemo implements Runnable { private Thread t; private String threadname; RunnableDemo( String name){ threadname = name; System.out.println("Creating " + threadname ); public void run() { System.out.println("Running " + threadname ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadname + ", " + i);

185 // Let the thread sleep for a while. Thread.sleep(50); catch (InterruptedException e) { System.out.println("Thread " + threadname + " interrupted."); System.out.println("Thread " + threadname + " exiting."); public void start () { System.out.println("Starting " + threadname ); if (t == null) { t = new Thread (this, threadname); t.start (); public class TestThread { public static void main(string args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); This would produce the following result: Creating Thread-1

186 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. Example: Here is the preceding program rewritten to extend Thread: class ThreadDemo extends Thread { private Thread t; private String threadname; ThreadDemo( String name){ threadname = name; System.out.println("Creating " + threadname ); public void run() { System.out.println("Running " + threadname ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadname + ", " + i); // Let the thread sleep for a while. Thread.sleep(50);

187 catch (InterruptedException e) { System.out.println("Thread " + threadname + " interrupted."); System.out.println("Thread " + threadname + " exiting."); public void start () { System.out.println("Starting " + threadname ); if (t == null) { t = new Thread (this, threadname); t.start (); public class TestThread { public static void main(string args[]) { ThreadDemo T1 = new ThreadDemo( "Thread-1"); T1.start(); ThreadDemo T2 = new ThreadDemo( "Thread-2"); T2.start(); This would produce the following result: Creating Thread-1 Starting Thread-1

188 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. Thread Methods: Following is the list of important methods available in the Thread class. SN Methods with Description 1 public void start() Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. 2 public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. 3 public final void setname(string name)

189 Changes the name of the Thread object. There is also a getname() method for retrieving the name. 4 public final void setpriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and public final void setdaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. 6 public final void join(long millisec) The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. 7 public void interrupt() Interrupts this thread, causing it to continue execution if it was blocked for any reason. 8 public final boolean isalive() Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

190 The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread. SN Methods with Description 1 public static void yield() Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled. 2 public static void sleep(long millisec) Causes the currently running thread to block for at least the specified number of milliseconds. 3 public static boolean holdslock(object x) Returns true if the current thread holds the lock on the given Object. 4 public static Thread currentthread() Returns a reference to the currently running thread, which is the thread that invokes this method. 5 public static void dumpstack() Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

191 How to create thread There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. 13. Create Thread by Extending Thread Class: The second way to create a thread is to create a new class that extendsthread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. Step 1 You will need to override run( ) method available in Thread class. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method: public void run( ) Step 2 Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method: void start( ); Following is another class which extends Thread class: 6. File Name : GuessANumber.java 7. Create a thread to extentd Thread public class GuessANumber extends Thread {

192 private int number; public GuessANumber(int number) { this.number = number; public void run() { int counter = 0; int guess = 0; do { guess = (int) (Math.random() * ); System.out.println(this.getName() + " guesses " + guess); counter++; while(guess!= number); System.out.println("** Correct! " + this.getname() + " in " + counter + " guesses.**"); Following is the main program which makes use of above defined classes: // File Name : ThreadClassDemo.java public class ThreadClassDemo { public static void main(string [] args) { Runnable hello = new DisplayMessage("Hello"); Thread thread1 = new Thread(hello); thread1.setdaemon(true); thread1.setname("hello"); System.out.println("Starting hello thread..."); thread1.start();

193 Runnable bye = new DisplayMessage("Goodbye"); Thread thread2 = new Thread(bye); thread2.setpriority(thread.min_priority); thread2.setdaemon(true); System.out.println("Starting goodbye thread..."); thread2.start(); System.out.println("Starting thread3..."); Thread thread3 = new GuessANumber(27); thread3.start(); try { thread3.join(); catch(interruptedexception e) { System.out.println("Thread interrupted."); System.out.println("Starting thread4..."); Thread thread4 = new GuessANumber(75); thread4.start(); System.out.println("main() is ending..."); This would produce the following result. You can try this example again and again and you would get different result every time. Starting hello thread... Starting goodbye thread... Hello Hello Hello

194 Hello Hello Hello Goodbye Goodbye Goodbye Goodbye Goodbye 2. Create Thread by Implementing Runnable Interface: If your class is intended to be executed as a thread then you can achieve this by implementing Runnable interface. You will need to follow three basic steps: Step 1: As a first step you need to implement a run() method provided by Runnableinterface. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method: public void run( ) Step 2: At second step you will instantiate a Thread object using the following constructor: Thread(Runnable threadobj, String threadname); Where, threadobj is an instance of a class that implements the Runnableinterface and threadname is the name given to the new thread. Step 3 Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method: void start( ); Example: The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable:

195 9. File Name : DisplayMessage.java 10. Create a thread to implement Runnable public class DisplayMessage implements Runnable { private String message; public DisplayMessage(String message) { this.message = message; public void run() { while(true) { System.out.println(message); Thread class: Thread class provide constructors and methods to create and perform operations on a thread.thread class extends Object class and implements Runnable interface. Commonly used Constructors of Thread class: Thread() Thread(String name) Thread(Runnable r) Thread(Runnable r,string name) Commonly used methods of Thread class: 3. public void run(): is used to perform action for a thread. 4. public void start(): starts the execution of the thread.jvm calls the run() method on the thread. 5. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. 6. public void join(): waits for a thread to die. 7. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

196 2 public int getpriority(): returns the priority of the thread. 3 public int setpriority(int priority): changes the priority of the thread. 4 public String getname(): returns the name of the thread. 5 public void setname(string name): changes the name of the thread. 6 public Thread currentthread(): returns the reference of currently executing thread. 7 public int getid(): returns the id of the thread. 8 public Thread.State getstate(): returns the state of the thread. 9 public boolean isalive(): tests if the thread is alive. 10 public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. 11 public void suspend(): is used to suspend the thread(depricated). 12 public void resume(): is used to resume the suspended thread(depricated). 13 public void stop(): is used to stop the thread(depricated). 14 public boolean isdaemon(): tests if the thread is a daemon thread. 15 public void setdaemon(boolean b): marks the thread as daemon or user thread. 16 public void interrupt(): interrupts the thread. 17 public boolean isinterrupted(): tests if the thread has been interrupted. 18 public static boolean interrupted(): tests if the current thread has been interrupted. Runnable interface: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). 1. public void run(): is used to perform action for a thread. Starting a thread: start() method of Thread class is used to start a newly created thread. It performs following tasks: A new thread starts(with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run. 1)By extending Thread class:

197 1. class Multi extends Thread{ 2. public void run(){ 3. System.out.println("thread is running..."); public static void main(string args[]){ 6. Multi t1=new Multi(); 7. t1.start(); Output:thread is running... Who makes your class object as thread object? Thread class constructor allocates a new thread object.when you create object of Multi class,your class constructor is invoked(provided by Compiler) fromwhere Thread class constructor is invoked(by super() as first statement).so your Multi class object is thread object now. 2)By implementing the Runnable interface: 1. class Multi3 implements Runnable{ 2. public void run(){ 3. System.out.println("thread is running..."); public static void main(string args[]){ 7. Multi3 m1=new Multi3(); 8. Thread t1 =new Thread(m1); 9. t1.start();

198 Output:thread is running... If you are not extending the Thread class,your class object would not be treated as a thread object.so you need to explicitely create Thread class object.we are passing the object of your class that implements Runnable so that your class run() method may execute. Thread Scheduler in Java Thread scheduler in java is the part of the JVM that decides which thread should run. There is no guarantee that which runnable thread will be chosen to run by the thread scheduler. Only one thread at a time can run in a single process. The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads. Difference between preemptive scheduling and time slicing Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. Sleep method in java The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

199 Syntax of sleep() method in java The Thread class provides two methods for sleeping a thread: o public static void sleep(long miliseconds)throws InterruptedException o public static void sleep(long miliseconds, int nanos)throws InterruptedException Example of sleep method in java 1. class TestSleepMethod1 extends Thread{ 2. public void run(){ 3. for(int i=1;i<5;i++){ 4. try{thread.sleep(500); 5. catch(interruptedexception e){system.out.println(e); 6. System.out.println(i); public static void main(string args[]){ 10. TestSleepMethod1 t1=new TestSleepMethod1(); 11. TestSleepMethod1 t2=new TestSleepMethod1(); t1.start(); 14. t2.start(); Output:

200 As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on. Can we start a thread twice No. After starting a thread, it can never be started again. If you does so, anillegalthreadstateexception is thrown. In such case, thread will run once but for second time, it will throw exception. Let's understand it by the example given below: 1. public class TestThreadTwice1 extends Thread{ 2. public void run(){ 3. System.out.println("running..."); public static void main(string args[]){ 6. TestThreadTwice1 t1=new TestThreadTwice1(); 7. t1.start(); 8. t1.start(); Test it Now running Exception in thread "main" java.lang.illegalthreadstateexception

201 What if we call run() method directly instead start() method? Each thread starts in a separate call stack. Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack. 1. class TestCallRun1 extends Thread{ 2. public void run(){ 3. System.out.println("running..."); public static void main(string args[]){ 6. TestCallRun1 t1=new TestCallRun1(); 7. t1.run();//fine, but does not start a separate call stack Test it Now Output:running... Problem if you direct call run() method 1. class TestCallRun2 extends Thread{ 2. public void run(){ 3. for(int i=1;i<5;i++){ 4. try{thread.sleep(500);catch(interruptedexception e){system.out.println(e); 5. System.out.println(i); 6.

202 7. 8. public static void main(string args[]){ 9. TestCallRun2 t1=new TestCallRun2(); 10. TestCallRun2 t2=new TestCallRun2(); t1.run(); 13. t2.run(); Test it Now Output: As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not thread object. The join() method: The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. Syntax: public void join()throws InterruptedException

203 public void join(long milliseconds)throws InterruptedException Example of join() method 1. class TestJoinMethod1 extends Thread{ 2. public void run(){ 3. for(int i=1;i<=5;i++){ 4. try{ 5. Thread.sleep(500); 6. catch(exception e){system.out.println(e); 7. System.out.println(i); public static void main(string args[]){ 11. TestJoinMethod1 t1=new TestJoinMethod1(); 12. TestJoinMethod1 t2=new TestJoinMethod1(); 13. TestJoinMethod1 t3=new TestJoinMethod1(); 14. t1.start(); 15. try{ 16. t1.join(); 17. catch(exception e){system.out.println(e); t2.start(); 20. t3.start(); Test it Now Output:1

204 As you can see in the above example,when t1 completes its task then t2 and t3 starts executing. Example of join(long miliseconds) method 1. class TestJoinMethod2 extends Thread{ 2. public void run(){ 3. for(int i=1;i<=5;i++){ 4. try{ 5. Thread.sleep(500); 6. catch(exception e){system.out.println(e); 7. System.out.println(i); public static void main(string args[]){ 11. TestJoinMethod2 t1=new TestJoinMethod2(); 12. TestJoinMethod2 t2=new TestJoinMethod2();

205 13. TestJoinMethod2 t3=new TestJoinMethod2(); 14. t1.start(); 15. try{ 16. t1.join(1500); 17. catch(exception e){system.out.println(e); t2.start(); 20. t3.start(); Test it Now Output: In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing.

206 getname(),setname(string) and getid() method: public String getname() public void setname(string name) public long getid() 1. class TestJoinMethod3 extends Thread{ 2. public void run(){ 3. System.out.println("running..."); public static void main(string args[]){ 6. TestJoinMethod3 t1=new TestJoinMethod3(); 7. TestJoinMethod3 t2=new TestJoinMethod3(); 8. System.out.println("Name of t1:"+t1.getname()); 9. System.out.println("Name of t2:"+t2.getname()); 10. System.out.println("id of t1:"+t1.getid()); t1.start(); 13. t2.start(); t1.setname("sonoo Jaiswal"); 16. System.out.println("After changing name of t1:"+t1.getname()); Test it Now Output:Name of t1:thread- 0 Name of t2:thread-1 id of t1:8 running...

207 After changling name of t1:sonoo Jaiswal running... The currentthread() method: The currentthread() method returns a reference to the currently executing thread object. Syntax: public static Thread currentthread() Example of currentthread() method 1. class TestJoinMethod4 extends Thread{ 2. public void run(){ 3. System.out.println(Thread.currentThread().getName()); public static void main(string args[]){ 7. TestJoinMethod4 t1=new TestJoinMethod4(); 8. TestJoinMethod4 t2=new TestJoinMethod4(); t1.start(); 11. t2.start(); Test it Now Output:Thread-0 Thread-1

208 Naming a thread: The Thread class provides methods to change and get the name of a thread. 1. public String getname(): is used to return the name of a thread. 2. public void setname(string name): is used to change the name of a thread. Example of naming a thread: 1. class TestMultiNaming1 extends Thread{ 2. public void run(){ 3. System.out.println("running..."); public static void main(string args[]){ 6. TestMultiNaming1 t1=new TestMultiNaming1(); 7. TestMultiNaming1 t2=new TestMultiNaming1(); 8. System.out.println("Name of t1:"+t1.getname()); 9. System.out.println("Name of t2:"+t2.getname()); t1.start(); 12. t2.start(); t1.setname("sonoo Jaiswal"); 15. System.out.println("After changing name of t1:"+t1.getname()); Test it Now Output:Name of t1:thread- 0 Name of t2:thread-1 id of t1:8 running... After changeling name of t1:sonoo Jaiswal running...

209 Daemon Thread in Java Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically. There are many java daemon threads running automatically e.g. gc, finalizer etc. You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc. Points to remember for Daemon Thread in Java It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads. Its life depends on user threads. It is a low priority thread. Why JVM terminates the daemon thread if there is no user thread? The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread. Methods for Java Daemon thread by Thread class The java.lang.thread class provides two methods for java daemon thread. No. Method Description 1) public void setdaemon(boolean is used to mark the current thread as daemon status) thread or user thread.

210 2) public boolean isdaemon() is used to check that current is daemon. Simple example of Daemon thread in java File: MyThread.java 1. public class TestDaemonThread1 extends Thread{ 2. public void run(){ 3. if(thread.currentthread().isdaemon()){//checking for daemon thread 4. System.out.println("daemon thread work"); else{ 7. System.out.println("user thread work"); public static void main(string[] args){ 11. TestDaemonThread1 t1=new TestDaemonThread1();//creating thread 12. TestDaemonThread1 t2=new TestDaemonThread1(); 13. TestDaemonThread1 t3=new TestDaemonThread1(); t1.setdaemon(true);//now t1 is daemon thread 16. t1.start();//starting threads t2.start(); t3.start(); Test it Now Output daemon thread work user thread work user thread work

211 Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException. File: MyThread.java 6. class TestDaemonThread2 extends Thread{ 7. public void run(){ 8. System.out.println("Name: "+Thread.currentThread().getName()); 9. System.out.println("Daemon: "+Thread.currentThread().isDaemon()); public static void main(string[] args){ 8. TestDaemonThread2 t1=new TestDaemonThread2(); 9. TestDaemonThread2 t2=new TestDaemonThread2(); 10. t1.start(); 11. t1.setdaemon(true);//will throw exception here 12. t2.start(); Test it Now Output:exception in thread main: java.lang.illegalthreadstateexception Java - Networking The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network. The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand. The java.net package provides support for the two common network protocols:

212 TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications. This tutorial gives good understanding on the following two subjects: Socket Programming: This is most widely used concept in Networking and it has been explained in very detail. URL Processing: This would be covered separately. Click here to learn about URL Processing in Java language. Socket Programming: Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket. The java.net.socket class represents a socket, and the java.net.serversocket class provides a mechanism for the server program to listen for clients and establish connections with them. The following steps occur when establishing a TCP connection between two computers using sockets: The server instantiates a ServerSocket object, denoting which port number communication is to occur on. The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port. After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.

213 The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server. On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket. After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream. TCP is a twoway communication protocol, so data can be sent across both streams at the same time. There are following usefull classes providing complete set of methods to implement sockets. ServerSocket Class Methods: The java.net.serversocket class is used by server applications to obtain a port and listen for client requests The ServerSocket class has four constructors: SN Methods with Description 1 public ServerSocket(int port) throws IOException Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application. 2 public ServerSocket(int port, int backlog) throws IOException Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue. 17. public ServerSocket(int port, int backlog, InetAddress address) throws IOException Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to

214 specify which of its IP addresses to accept client requests on 4 public ServerSocket() throws IOException Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is ready for client requests. Here are some of the common methods of the ServerSocket class: SN Methods with Description 1 public int getlocalport() Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you. 2 public Socket accept() throws IOException Waits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setsotimeout() method. Otherwise, this method blocks indefinitely 3 public void setsotimeout(int timeout) Sets the time-out value for how long the server socket waits for a client during the accept(). 4 public void bind(socketaddress host, int backlog) Binds the socket to the specified server and port in the SocketAddress object. Use this method if you instantiated the ServerSocket using the

215 no-argument constructor. When the ServerSocket invokes accept(), the method does not return until a client connects. After a client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. A TCP connection now exists between the client and server, and communication can begin. Socket Class Methods: The java.net.socket class represents the socket that both the client and server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method. The Socket class has five constructors that a client uses to connect to a server: SN Methods with Description 1 public Socket(String host, int port) throws UnknownHostException, IOException. This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server. 2 public Socket(InetAddress host, int port) throws IOException This method is identical to the previous constructor, except that the host is denoted by an InetAddress object. 3 public Socket(String host, int port, InetAddress localaddress, int localport) throws IOException. Connects to the specified host and port, creating a socket on the local host at the specified address and port. 4 public Socket(InetAddress host, int port, InetAddress localaddress, int localport) throws IOException.

216 This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String 5 public Socket() Creates an unconnected socket. Use the connect() method to connect this socket to a server. When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port. Some methods of interest in the Socket class are listed here. Notice that both the client and server have a Socket object, so these methods can be invoked by both the client and server. SN Methods with Description 1 public void connect(socketaddress host, int timeout) throws IOException This method connects the socket to the specified host. This method is needed only when you instantiated the Socket using the no-argument constructor. 2 public InetAddress getinetaddress() This method returns the address of the other computer that this socket is connected to. 3 public int getport() Returns the port the socket is bound to on the remote machine. 4 public int getlocalport() Returns the port the socket is bound to on the local machine.

217 5 public SocketAddress getremotesocketaddress() Returns the address of the remote socket. 6 public InputStream getinputstream() throws IOException Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket. 7 public OutputStream getoutputstream() throws IOException Returns the output stream of the socket. The output stream is connected to the input stream of the remote socket 8 public void close() throws IOException Closes the socket, which makes this Socket object no longer capable of connecting again to any server InetAddress Class Methods: This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would need while doing socket programming: SN Methods with Description 1 static InetAddress getbyaddress(byte[] addr) Returns an InetAddress object given the raw IP address. 2 static InetAddress getbyaddress(string host, byte[] addr) Create an InetAddress based on the provided host name and IP address. 3 static InetAddress getbyname(string host)

218 Determines the IP address of a host, given the host's name. 4 String gethostaddress() Returns the IP address string in textual presentation. 5 String gethostname() Gets the host name for this IP address. 11. static InetAddress InetAddress getlocalhost() Returns the local host. 12. String tostring() Converts this IP address to a String. Socket Client Example: The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response. // File Name GreetingClient.java import java.net.*; import java.io.*; public class GreetingClient { public static void main(string [] args) { String servername = args[0]; int port = Integer.parseInt(args[1]); try {

219 System.out.println("Connecting to " + servername + " on port " + port); Socket client = new Socket(serverName, port); System.out.println("Just connected to " + client.getremotesocketaddress()); OutputStream outtoserver = client.getoutputstream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeutf("hello from " + client.getlocalsocketaddress()); InputStream infromserver = client.getinputstream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readutf()); client.close(); catch(ioexception e) { e.printstacktrace(); Socket Server Example: The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument: // File Name GreetingServer.java import java.net.*; import java.io.*; public class GreetingServer extends Thread {

220 private ServerSocket serversocket; public GreetingServer(int port) throws IOException { serversocket = new ServerSocket(port); serversocket.setsotimeout(10000); public void run() { while(true) { try { System.out.println("Waiting for client on port " + serversocket.getlocalport() + "..."); Socket server = serversocket.accept(); System.out.println("Just connected to " + server.getremotesocketaddress()); DataInputStream in = new DataInputStream(server.getInputStream()); System.out.println(in.readUTF()); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeutf("thank you for connecting to " + server.getlocalsocketaddress() + "\ngoodbye!"); server.close(); catch(sockettimeoutexception s) { System.out.println("Socket timed out!"); break; catch(ioexception e) {

221 e.printstacktrace(); break; public static void main(string [] args) { int port = Integer.parseInt(args[0]); try { Thread t = new GreetingServer(port); t.start(); catch(ioexception e) { e.printstacktrace(); Compile client and server and then start server as follows: $ java GreetingServer 6066 Waiting for client on port Check client program as follows: $ java GreetingClient localhost 6066 Connecting to localhost on port 6066 Just connected to localhost/ :6066 Server says Thank you for connecting to / :6066 Goodbye! UNIT V Database Connectivity Drivers in Java JDBC, ODBC connectivity (database connectivity)

222 Java JDBC Tutorial Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database. Why use JDBC Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language). Do You Know o How to connect Java application with Oracle and Mysql database using JDBC? o What is the difference between Statement and PreparedStatement interface? o How to print total numbers of tables and views of a database using JDBC? o How to store and retrieve images from Oracle database using JDBC? o How to store and retrieve files from Oracle database using JDBC?

223 What is API API (Application programming interface) is a document that contains description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other. An API can be created for applications, libraries, operating systems, etc Topics in Java JDBC 2) JDBC Drivers 4 types of JDBC drivers, their advantages and disadvantages. 3) 5 Steps to connect to the database The 5 steps to connect to the database in java using JDBC. 4) Connectivity with Oracle using JDBC We will connect a simple java program with the oracle database. 5) Connectivity with MySQL using JDBC We will connect a simple java program with the mysql database. 6) Connectivity with Access without DSN Let's connect java application with access database with and without DSN. 7) DriverManager class In this JDBC tutorial, we will learn what does the DriverManager class and what are its methods.

224 8) Connection interface We will learn what is Connection interface and what are its methods. 9) Statement interface We will learn what is Statement interface and what are its methods. 10) ResultSet interface We will learn what is ResultSet interface and what are its methods. Moreover, we will learn how we can make the ResultSet scrollable. 11) PreparedStatement Interface We will learn what is benefit of PreparedStatement over Statement interface. We will see examples to insert, update or delete records using the PreparedStatement interface. 12) ResultSetMetaData interface We will learn how we can get the metadata of a table. 13) DatabaseMetaData interface We will learn how we can get the metadata of a database. 14) Storing image in Oracle How to store image in the oracle database using JDBC. 15) Retrieving image from Oracle

225 To retrieve image from the oracle database using JDBC. 16) Storing file in Oracle To store file in the oracle database using JDBC. 17) Retrieving file from Oracle To retrieve file from the oracle database using JDBC. 18) CallableStatement To call stored procedures and functions using CallableStatement. 19) Transaction Management using JDBC To use transaction management using JDBC. 16. Batch Statement using JDBC The code to execute batch of queries. 17. JDBC RowSet The working of new JDBC RowSet interface. JDBC Driver JDBC Driver is a software component that enables java application to interact with the database.there are 4 types of JDBC drivers: 6) JDBC-ODBC bridge driver 7) Native-API driver (partially java driver) 8) Network Protocol driver (fully java driver)

226 Thin driver (fully java driver) 1) JDBC-ODBC bridge driver The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC- ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver. Advantages: easy to use. can be easily connected to any database. Disadvantages: Performance degraded because JDBC method call is converted into the ODBC function calls. The ODBC driver needs to be installed on the client machine. 2) Native-API driver The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.

227 Advantage: performance upgraded than JDBC-ODBC bridge driver. Disadvantage: The Native driver needs to be installed on the each client machine. The Vendor client library needs to be installed on client machine. 14. Network Protocol driver The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.

228 Advantage: No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc. Disadvantages: Network support is required on client machine. Requires database-specific coding to be done in the middle tier. Maintenance of Network Protocol driver becomes costly because it requires databasespecific coding to be done in the middle tier. 4) Thin driver The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.

229 Advantage: Better performance than all other drivers. No software is required at client side or server side. Disadvantage: Drivers depends on the Database. 5 Steps to connect to the database in java There are 5 steps to connect any java application with the database in java using JDBC. They are as follows: Register the driver class Creating connection Creating statement Executing queries Closing connection

230 1) Register the driver class The forname() method of Class class is used to register the driver class. This method is used to dynamically load the driver class. Syntax of forname() method public static void forname(string classname)throws ClassNotFoundException Example to register the OracleDriver class 1. Class.forName("oracle.jdbc.driver.OracleDriver"); 2) Create the connection object The getconnection() method of DriverManager class is used to establish connection with the database. Syntax of getconnection() method 1. 1) public static Connection getconnection(string url)throws SQLException 2. 2) public static Connection getconnection(string url,string name,string password) 3. throws SQLException Example to establish connection with the Oracle database 1. Connection con=drivermanager.getconnection( 2. 3) Create the Statement object The createstatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database. Syntax of createstatement() method 1. public Statement createstatement()throws SQLException Example to create the statement object 1. Statement stmt=con.createstatement();

231 4) Execute the query The executequery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table. Syntax of executequery() method public ResultSet executequery(string sql)throws SQLException Example to execute query 1. ResultSet rs=stmt.executequery("select * from emp"); while(rs.next()){ 4. System.out.println(rs.getInt(1)+" "+rs.getstring(2)); 5. 5) Close the connection object By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection. Syntax of close() method 1. public void close()throws SQLException Example to close connection 1. con.close(); Example to connect to the Oracle database For connecting java application with the oracle database, you need to follow 5 steps to perform database connectivity. In this example we are using Oracle10g as the database. So we need to know following informations for the oracle database: 1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.oracledriver. 2. Connection URL: The connection URL for the oracle10g database is

232 where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. You may get all these informations from the tnsnames.ora file. 3. Username: The default username for the oracle database is system. 4. Password: Password is given by the user at the time of installing the oracle database. Let's first create a table in oracle database. 1. create table emp(id number(10),name varchar2(40),age number(3)); Example to Connect Java Application with Oracle database In this example, system is the username and oracle is the password of the Oracle database. 1. import java.sql.*; 2. class OracleCon{ 3. public static void main(string args[]){ 4. try{ 5. //step1 load the driver class 6. Class.forName("oracle.jdbc.driver.OracleDriver"); 7. 2) //step2 create the connection object 3) Connection con=drivermanager.getconnection( 4) "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); 5) 6) //step3 create the statement object 7) Statement stmt=con.createstatement(); 8) 9) //step4 execute query 10) ResultSet rs=stmt.executequery("select * from emp"); 11) while(rs.next()) 12) System.out.println(rs.getInt(1)+" "+rs.getstring(2)+" "+rs.getstring(3));

233 //step5 close the connection object 21. con.close(); catch(exception e){ System.out.println(e); The above example will fetch all the records of emp table. To connect java application with the Oracle database ojdbc14.jar file is required to be loaded. Two ways to load the jar file: 1. paste the ojdbc14.jar file in jre/lib/ext folder 2. set classpath 8. paste the ojdbc14.jar file in JRE/lib/ext folder: Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here. 2) set classpath: There are two ways to set the classpath: temporary permanent How to set the temporary classpath: Firstly, search the ojdbc14.jar file then open command prompt and write: 1. C:>set classpath=c:\folder\ojdbc14.jar;.; How to set the permanent classpath: Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.; To see the slides of seting parmanent path click here

234 Example to connect to the mysql database For connecting java application with the mysql database, you need to follow 5 steps to perform database connectivity. In this example we are using MySql as the database. So we need to know following informations for the mysql database: 11. Driver class: The driver class for the mysql database is com.mysql.jdbc.driver. 12. Connection URL: The connection URL for the mysql database isjdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name. We may use any database, in such case, you need to replace the sonoo with your database name. 13. Username: The default username for the mysql database is root. 14. Password: Password is given by the user at the time of installing the mysql database. In this example, we are going to use root as the password. Let's first create a table in the mysql database, but before creating table, we need to create database first. 10. create database sonoo; 11. use sonoo; 12. create table emp(id int(10),name varchar(40),age int(3)); Example to Connect Java Application with mysql database In this example, sonoo is the database name, root is the username and password. 1. import java.sql.*; 2. class MysqlCon{ 3. public static void main(string args[]){ 4. try{ 5. Class.forName("com.mysql.jdbc.Driver"); 6. Connection con=drivermanager.getconnection( "jdbc:mysql://localhost:3306/sonoo","root","root"); //here sonoo is database name, root is username and password Statement stmt=con.createstatement(); ResultSet rs=stmt.executequery("select * from emp"); while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getstring(2)+" "+rs.getstring(3));

235 con.close(); catch(exception e){ System.out.println(e); 22. The above example will fetch all the records of emp table. To connect java application with the mysql database mysqlconnector.jar file is required to be loaded. Two ways to load the jar file: paste the mysqlconnector.jar file in jre/lib/ext folder set classpath 23. paste the mysqlconnector.jar file in JRE/lib/ext folder: Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here. 2) set classpath: There are two ways to set the classpath: temporary permament How to set the temporary classpath open comman prompt and write: 1. C:>set classpath=c:\folder\mysql-connector-java bin.jar;.; How to set the permanent classpath Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:\folder\mysql-connector-java bin.jar;.;

236 Connectivity with Access without DSN There are two ways to connect java application with the access database. 11. Without DSN (Data Source Name) 12. With DSN Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only for knowledge. Example to Connect Java Application with access without DSN In this example, we are going to connect the java program with the access database. In such case, we have created the login table in the access database. There is only one column in the table named name. Let's get all the name of the login table. 5. import java.sql.*; 6. class Test{ 7. public static void main(string ar[]){ 8. try{ 9. String database="student.mdb";//here database exists in the current directory String url="jdbc:odbc:driver={microsoft Access Driver (*.mdb); 8. DBQ=" + database + ";DriverID=22;READONLY=true"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 13. Connection c=drivermanager.getconnection(url); 14. Statement st=c.createstatement(); 15. ResultSet rs=st.executequery("select * from login"); while(rs.next()){ 6. System.out.println(rs.getString(1)); catch(exception ee){system.out.println(ee); Example to Connect Java Application with access with DSN Connectivity with type1 driver is not considered good. To connect java application with type1 driver, create DSN first, here we are assuming your dsn name is mydsn.

237 10. import java.sql.*; 11. class Test{ 12. public static void main(string ar[]){ 13. try{ 14. String url="jdbc:odbc:mydsn"; 15. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 16. Connection c=drivermanager.getconnection(url); 17. Statement st=c.createstatement(); 18. ResultSet rs=st.executequery("select * from login"); while(rs.next()){ 6. System.out.println(rs.getString(1)); catch(exception ee){system.out.println(ee); DriverManager class: The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver(). Commonly used methods of DriverManager class: 10. public static void registerdriver(driver driver): is used to register the given driver with DriverManager. 11. public static void deregisterdriver(driver driver): is used to deregister the given driver (drop the driver from the list) with

238 DriverManager. 3) public static Connection is used to establish the connection with getconnection(string url): the specified url. 4) public static Connection is used to establish the connection with getconnection(string url,string username,string password): the specified url, username and password. Connection interface: A Connection is the session between java application and database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit(),rollback() etc. By default, connection commits the changes after executing queries. Commonly used methods of Connection interface: 9. public Statement createstatement(): creates a statement object that can be used to execute SQL queries. 10. public Statement createstatement(int resultsettype,int resultsetconcurrency): Creates a Statement object that will generate ResultSet objects with the given type and concurrency. 11. public void setautocommit(boolean status): is used to set the commit status.by default it is true. 12. public void commit(): saves the changes made since the previous commit/rollback permanent. 13. public void rollback(): Drops all changes made since the previous commit/rollback. 14. public void close(): closes the connection and Releases a JDBC resources immediately.

239 Statement interface The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet. Commonly used methods of Statement interface: The important methods of Statement interface are as follows: 2 public ResultSet executequery(string sql): is used to execute SELECT query. It returns the object of ResultSet. 3 public int executeupdate(string sql): is used to execute specified query, it may be create, drop, insert, update, delete etc. 4 public boolean execute(string sql): is used to execute queries that may return multiple results. 5 public int[] executebatch(): is used to execute batch of commands. Example of Statement interface Let s see the simple example of Statement interface to insert, update and delete the record. 1. import java.sql.*; 2. class FetchRecord{ 3. public static void main(string args[])throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); 6. Connection con=drivermanager.getconnection("jdbc:oracle:thin:@localhost:1521:xe","syste m","oracle"); 7. Statement stmt=con.createstatement(); //stmt.executeupdate("insert into emp765 values(33,'irfan',50000)"); 10. //int result=stmt.executeupdate("update emp765 set name='vimal',salary=10000 where id =33"); 11. int result=stmt.executeupdate("delete from emp765 where id=33");

240 System.out.println(result+" records affected"); 14. con.close(); 15. ResultSet interface The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row. By default, ResultSet object can be moved forward only and it is not updatable. But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createstatement(int,int) method as well as we can make this object as updatable by: 1. Statement stmt = con.createstatement(resultset.type_scroll_insensitive, 2. ResultSet.CONCUR_UPDATABLE); Commonly used methods of ResultSet interface 1) public boolean next(): is used to move the cursor to the one row next from the current position. 2) public boolean previous(): is used to move the cursor to the one row previous from the current position. 3) public boolean first(): is used to move the cursor to the first row in result set object. 4) public boolean last(): is used to move the cursor to the last row in result set object. 5) public boolean absolute(int is used to move the cursor to the specified row row): number in the ResultSet object. 6) public boolean relative(int is used to move the cursor to the relative row number in the ResultSet object, it may be positive or

241 row): negative. 7) public int getint(int is used to return the data of specified column index columnindex): of the current row as int. 8) public int getint(string is used to return the data of specified column name columnname): of the current row as int. 9) public String getstring(int is used to return the data of specified column index columnindex): of the current row as String. 10) public String getstring(string is used to return the data of specified column name columnname): of the current row as String. Example of Scrollable ResultSet Let s see the simple example of ResultSet interface to retrieve the data of 3rd row. 1. import java.sql.*; 2. class FetchRecord{ 3. public static void main(string args[])throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); 6. Connection con=drivermanager.getconnection("jdbc:oracle:thin:@localhost:1521:xe","syste m","oracle"); 7. Statement stmt=con.createstatement(resultset.type_scroll_sensitive,resultset.conc UR_UPDATABLE); 8. ResultSet rs=stmt.executequery("select * from emp765"); //getting the record of 3rd row 11. rs.absolute(3);

242 12. System.out.println(rs.getString(1)+" "+rs.getstring(2)+" "+rs.getstring(3)); con.close(); 15. PreparedStatement interface The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query. Let's see the example of parameterized query: 1. String sql="insert into emp values(?,?,?)"; As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement. Why use PreparedStatement? Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once. How to get the instance of PreparedStatement? The preparestatement() method of Connection interface is used to return the object of PreparedStatement. Syntax: 1. public PreparedStatement preparestatement(string query)throws SQLException{

243 Methods of PreparedStatement interface The important methods of PreparedStatement interface are given below: Method Description public void setint(int paramindex, int value) sets the integer value to the given parameter index. public void setstring(int paramindex, String value) sets the String value to the given parameter index. public void setfloat(int paramindex, float value) sets the float value to the given parameter index. public void setdouble(int paramindex, double value) sets the double value to the given parameter index. public int executeupdate() executes the query. It is used for create, drop, insert, update, delete etc. public ResultSet executequery() executes the select query. It returns an instance of ResultSet. Example of PreparedStatement interface that inserts the record First of all create table as given below: 1. create table emp(id number(10),name varchar2(50)); Now insert records in this table by the code given below: 1. import java.sql.*; 2. class InsertPrepared{ 3. public static void main(string args[]){ 4. try{ 5. Class.forName("oracle.jdbc.driver.OracleDriver");

244 6. 7. Connection m","oracle"); PreparedStatement stmt=con.preparestatement("insert into Emp values(?,?)"); 10. stmt.setint(1,101);//1 specifies the first parameter in the query 11. stmt.setstring(2,"ratan"); int i=stmt.executeupdate(); 14. System.out.println(i+" records inserted"); con.close(); catch(exception e){ System.out.println(e); Example of PreparedStatement interface that updates the record 1. PreparedStatement stmt=con.preparestatement("update emp set name=? where id=?"); 2. stmt.setstring(1,"sonoo");//1 specifies the first parameter in the query i.e. name 3. stmt.setint(2,101); int i=stmt.executeupdate(); 6. System.out.println(i+" records updated"); Example of PreparedStatement interface that deletes the record 1. PreparedStatement stmt=con.preparestatement("delete from emp where id=?"); 2. stmt.setint(1,101); int i=stmt.executeupdate(); 5. System.out.println(i+" records deleted");

245 Example of PreparedStatement interface that retrieve the records of a table 1. PreparedStatement stmt=con.preparestatement("select * from emp"); 2. ResultSet rs=stmt.executequery(); 3. while(rs.next()){ 4. System.out.println(rs.getInt(1)+" "+rs.getstring(2)); 5. Example of PreparedStatement to insert records until user press n 1. import java.sql.*; 2. import java.io.*; 3. class RS{ 4. public static void main(string args[])throws Exception{ 5. Class.forName("oracle.jdbc.driver.OracleDriver"); 6. Connection con=drivermanager.getconnection("jdbc:oracle:thin:@localhost:1521:xe","syste m","oracle"); PreparedStatement ps=con.preparestatement("insert into emp130 values(?,?,?)"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); do{ 13. System.out.println("enter id:"); 14. int id=integer.parseint(br.readline()); 15. System.out.println("enter name:"); 16. String name=br.readline(); 17. System.out.println("enter salary:"); 18. float salary=float.parsefloat(br.readline()); ps.setint(1,id); 21. ps.setstring(2,name); 22. ps.setfloat(3,salary); 23. int i=ps.executeupdate(); 24. System.out.println(i+" records affected"); System.out.println("Do you want to continue: y/n"); 27. String s=br.readline(); 28. if(s.startswith("n")){ 29. break; while(true); con.close(); 34.

246 ResultSetMetaData Interface The metadata means data about data i.e. we can get further information from the data. If you have to get metadata of a table like total number of column, column name, column type etc., ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object. Commonly used methods of ResultSetMetaData interface Method Description public int getcolumncount()throws SQLException it returns the total number of columns in the ResultSet object. public String getcolumnname(int index)throws SQLException it returns the column name of the specified column index. public String getcolumntypename(int index)throws SQLException it returns the column type name for the specified index. public String gettablename(int index)throws SQLException it returns the table name for the specified column index. How to get the object of ResultSetMetaData: The getmetadata() method of ResultSet interface returns the object of ResultSetMetaData. Syntax: 1. public ResultSetMetaData getmetadata()throws SQLException Example of ResultSetMetaData interface : 1. import java.sql.*; 2. class Rsmd{ 3. public static void main(string args[]){ 4. try{ 5. Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=drivermanager.getconnection(

247 PreparedStatement ps=con.preparestatement("select * from emp"); 11. ResultSet rs=ps.executequery(); ResultSetMetaData rsmd=rs.getmetadata(); System.out.println("Total columns: "+rsmd.getcolumncount()); 16. System.out.println("Column Name of 1st column: "+rsmd.getcolumnname(1)); 17. System.out.println("Column Type Name of 1st column: "+rsmd.getcolumntypename(1)); con.close(); catch(exception e){ System.out.println(e); Output:Total columns: 2 Column Name of 1st column: ID Column Type Name of 1st column: NUMBER DatabaseMetaData interface: DatabaseMetaData interface provides methods to get meta data of a database such as database product name, database product version, driver name, name of total number of tables, name of total number of views etc. Commonly used methods of DatabaseMetaData interface public String getdrivername()throws SQLException: it returns the name of the JDBC driver. public String getdriverversion()throws SQLException: it returns the version number of the JDBC driver. public String getusername()throws SQLException: it returns the username of the database. public String getdatabaseproductname()throws SQLException: it returns the product name of the database. public String getdatabaseproductversion()throws SQLException: it returns the product version of the database. public ResultSet gettables(string catalog, String schemapattern, String tablenamepattern, String[] types)throws SQLException: it returns the description of the tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.

248 How to get the object of DatabaseMetaData: The getmetadata() method of Connection interface returns the object of DatabaseMetaData. Syntax: 1. public DatabaseMetaData getmetadata()throws SQLException Simple Example of DatabaseMetaData interface : 1. import java.sql.*; 2. class Dbmd{ 3. public static void main(string args[]){ 4. try{ 5. Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=drivermanager.getconnection( 4. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); DatabaseMetaData dbmd=con.getmetadata(); System.out.println("Driver Name: "+dbmd.getdrivername()); 9. System.out.println("Driver Version: "+dbmd.getdriverversion()); 10. System.out.println("UserName: "+dbmd.getusername()); 11. System.out.println("Database Product Name: "+dbmd.getdatabaseproductname()); 12. System.out.println("Database Product Version: "+dbmd.getdatabaseproductversion()); con.close(); catch(exception e){ System.out.println(e); Output:Driver Name: Oracle JDBC Driver Driver Version: XE Database Product Name: Oracle Database Product Version: Oracle Database 10g Express Edition Release Production Example of DatabaseMetaData interface that prints total number of tables : 1. import java.sql.*; 2. class Dbmd2{ 3. public static void main(string args[]){ 4. try{ 5. Class.forName("oracle.jdbc.driver.OracleDriver");

249 6. 7. Connection con=drivermanager.getconnection( DatabaseMetaData dbmd=con.getmetadata(); 11. String table[]={"table"; 12. ResultSet rs=dbmd.gettables(null,null,null,table); while(rs.next()){ 15. System.out.println(rs.getString(3)); con.close(); catch(exception e){ System.out.println(e); Example of DatabaseMetaData interface that prints total number of views : 1. import java.sql.*; 2. class Dbmd3{ 3. public static void main(string args[]){ 4. try{ 5. Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=drivermanager.getconnection( 8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); DatabaseMetaData dbmd=con.getmetadata(); 11. String table[]={"view"; 12. ResultSet rs=dbmd.gettables(null,null,null,table); while(rs.next()){ 15. System.out.println(rs.getString(3)); con.close(); catch(exception e){ System.out.println(e);

250 Example to retrieve image from Oracle database By the help of PreparedStatement we can retrieve and store the image in the database. The getblob() method of PreparedStatement is used to get Binary information, it returns the instance of Blob. After calling the getbytes() method on the blob object, we can get the array of binary information that can be written into the image file. Signature of getblob() method of PreparedStatement 1. public Blob getblob()throws SQLException Signature of getbytes() method of Blob interface 1. public byte[] getbytes(long pos, int length)throws SQLException We are assuming that image is stored in the imgtable. 1. CREATE TABLE "IMGTABLE" 2. ( "NAME" VARCHAR2(4000), 3. "PHOTO" BLOB 4. ) 5. / Now let's write the code to retrieve the image from the database and write it into the directory so that it can be displayed. In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed by the img tag. 1. import java.sql.*; 2. import java.io.*; 3. public class RetrieveImage { 4. public static void main(string[] args) { 5. try{ 6. Class.forName("oracle.jdbc.driver.OracleDriver"); 7. Connection con=drivermanager.getconnection( 8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement ps=con.preparestatement("select * from imgtable"); 11. ResultSet rs=ps.executequery(); 12. if(rs.next()){//now on 1st row Blob b=rs.getblob(2);//2 means 2nd column data 15. byte barr[]=b.getbytes(1,(int)b.length());//1 means first image 16.

251 17. FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");

252 18. fout.write(barr); fout.close(); 21. //end of if 22. System.out.println("ok"); con.close(); 25. catch (Exception e) {e.printstacktrace(); Now if you see the d drive, sonoo.jpg image is created. Example to store file in Oracle database: The setcharacterstream() method of PreparedStatement is used to set character information into the parameterindex. Syntax: 1) public void setbinarystream(int paramindex,inputstream stream)throws SQLException 2) public void setbinarystream(int paramindex,inputstream stream,long length)throws SQLException For storing file into the database, CLOB (Character Large Object) datatype is used in the table. For example: 1. CREATE TABLE "FILETABLE" 2. ( "ID" NUMBER, 3. "NAME" CLOB 4. ) 5. / 1. import java.io.*; 2. import java.sql.*; public class StoreFile { 5. public static void main(string[] args) { 6. try{ 7. Class.forName("oracle.jdbc.driver.OracleDriver"); 8. Connection con=drivermanager.getconnection( 9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement ps=con.preparestatement( 12. "insert into filetable values(?,?)"); 13.

253 14. File f=new File("d:\\myfile.txt"); 15. FileReader fr=new FileReader(f); ps.setint(1,101); 18. ps.setcharacterstream(2,fr,(int)f.length()); 19. int i=ps.executeupdate(); 20. System.out.println(i+" records affected"); con.close(); catch (Exception e) {e.printstacktrace(); Example to retrieve file from Oracle database: The getclob() method of PreparedStatement is used to get file information from the database. Syntax of getclob method 1. public Clob getclob(int columnindex){ Let's see the table structure of this example to retrieve the file. 1. CREATE TABLE "FILETABLE" 2. ( "ID" NUMBER, 3. "NAME" CLOB 4. ) 5. / The example to retrieve the file from the Oracle database is given below. 1. import java.io.*; 2. import java.sql.*; public class RetrieveFile { 5. public static void main(string[] args) { 6. try{ 7. Class.forName("oracle.jdbc.driver.OracleDriver"); 8. Connection con=drivermanager.getconnection( 9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement ps=con.preparestatement("select * from filetable");

254 12. ResultSet rs=ps.executequery();

255 13. rs.next();//now on 1st row Clob c=rs.getclob(2); 16. Reader r=c.getcharacterstream(); FileWriter fw=new FileWriter("d:\\retrivefile.txt"); int i; 21. while((i=r.read())!=-1) 22. fw.write((char)i); fw.close(); 25. con.close(); System.out.println("success"); 28. catch (Exception e) {e.printstacktrace(); CallableStatement Interface To call the stored procedures and functions, CallableStatement interface is used. We can have business logic on the database by the use of stored procedures and functions that will make the performance better because these are precompiled. Suppose you need the get the age of the employee based on the date of birth, you may create a function that receives date as the input and returns age of the employee as the output.

256 What is the difference between stored procedures and functions. The differences between stored procedures and functions are given below: Stored Procedure Function is used to perform business logic. is used to perform calculation. must not have the return type. must have the return type. may return 0 or more values. may return only one values. We can call functions from the procedure. Procedure cannot be called from function. Procedure supports input and output parameters. Function supports only input parameter. Exception handling using try/catch block can be used in stored procedures. Exception handling using try/catch can't be used in user defined functions. How to get the instance of CallableStatement? The preparecall() method of Connection interface returns the instance of CallableStatement. Syntax is given below: 1. public CallableStatement preparecall("{ call procedurename(?,?...?)"); The example to get the instance of CallableStatement is given below: 8. CallableStatement stmt=con.preparecall("{call myprocedure(?,?)"); It calls the procedure myprocedure that receives 2 arguments.

257 Full example to call the stored procedure using JDBC To call the stored procedure, you need to create it in the database. Here, we are assuming that stored procedure looks like this. 15. create or replace procedure "INSERTR" 16. (id IN NUMBER, 17. name IN VARCHAR2) 18. is 19. begin 20. insert into user420 values(id,name); 21. end; 22. / The table structure is given below: 1. create table user420(id number(10), name varchar2(200)); In this example, we are going to call the stored procedure INSERTR that receives id and name as the parameter and inserts it into the table user420. Note that you need to create the user420 table as well to run this application. 22. import java.sql.*; 23. public class Proc { 24. public static void main(string[] args) throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); 5. Connection con=drivermanager.getconnection( 6. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); CallableStatement stmt=con.preparecall("{call insertr(?,?)"); 17. stmt.setint(1,1011); 18. stmt.setstring(2,"amit"); 19. stmt.execute(); System.out.println("success"); Now check the table in the database, value is inserted in the user420 table. Example to call the function using JDBC In this example, we are calling the sum4 function that receives two input and returns the sum of the given number. Here, we have used the registeroutparameter method of

258 CallableStatement interface, that registers the output parameter with its corresponding type. It provides information to the CallableStatement about the type of result being displayed. The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE, BLOB, CLOB etc. Let's create the simple function in the database first. 6. create or replace function sum4 7. (n1 in number,n2 in number) 8. return number 9. is 10. temp number(8); 11. begin 12. temp :=n1+n2; 13. return temp; 14. end; 15. / Now, let's write the simple program to call the function. 1. import java.sql.*; public class FuncSum { 14. public static void main(string[] args) throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); 21. Connection con=drivermanager.getconnection( 22. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); CallableStatement stmt=con.preparecall("{?= call sum4(?,?)"); 25. stmt.setint(2,10); 26. stmt.setint(3,43); 27. stmt.registeroutparameter(1,types.integer); 28. stmt.execute(); System.out.println(stmt.getInt(1)); Output: 53

259 CallableStatement Interface To call the stored procedures and functions, CallableStatement interface is used. We can have business logic on the database by the use of stored procedures and functions that will make the performance better because these are precompiled. Suppose you need the get the age of the employee based on the date of birth, you may create a function that receives date as the input and returns age of the employee as the output. What is the difference between stored procedures and functions. The differences between stored procedures and functions are given below: Stored Procedure Function is used to perform business logic. is used to perform calculation. must not have the return type. must have the return type. may return 0 or more values. may return only one values. We can call functions from the procedure. Procedure cannot be called from function. Procedure supports input and output parameters. Function supports only input parameter. Exception handling using try/catch block can be used in stored procedures. Exception handling using try/catch can't be used in user defined functions.

260 How to get the instance of CallableStatement? The preparecall() method of Connection interface returns the instance of CallableStatement. Syntax is given below: 16. public CallableStatement preparecall("{ call procedurename(?,?...?)"); The example to get the instance of CallableStatement is given below: 8. CallableStatement stmt=con.preparecall("{call myprocedure(?,?)"); It calls the procedure myprocedure that receives 2 arguments. Full example to call the stored procedure using JDBC To call the stored procedure, you need to create it in the database. Here, we are assuming that stored procedure looks like this. 14. create or replace procedure "INSERTR" 15. (id IN NUMBER, 16. name IN VARCHAR2) 17. is 18. begin 19. insert into user420 values(id,name); 20. end; 21. / The table structure is given below: 1. create table user420(id number(10), name varchar2(200)); In this example, we are going to call the stored procedure INSERTR that receives id and name as the parameter and inserts it into the table user420. Note that you need to create the user420 table as well to run this application. 10. import java.sql.*; 11. public class Proc { 12. public static void main(string[] args) throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); 20. Connection con=drivermanager.getconnection( 21. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); CallableStatement stmt=con.preparecall("{call insertr(?,?)");

261 21. stmt.setint(1,1011); 22. stmt.setstring(2,"amit"); 23. stmt.execute(); System.out.println("success"); Now check the table in the database, value is inserted in the user420 table. Example to call the function using JDBC In this example, we are calling the sum4 function that receives two input and returns the sum of the given number. Here, we have used the registeroutparameter method of CallableStatement interface, that registers the output parameter with its corresponding type. It provides information to the CallableStatement about the type of result being displayed. The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE, BLOB, CLOB etc. Let's create the simple function in the database first. 7. create or replace function sum4 8. (n1 in number,n2 in number) 9. return number 10. is 11. temp number(8); 12. begin 13. temp :=n1+n2; 14. return temp; 15. end; 16. / Now, let's write the simple program to call the function. 1. import java.sql.*; public class FuncSum { 14. public static void main(string[] args) throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); 6. Connection con=drivermanager.getconnection( 7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); 8.

262 13. CallableStatement stmt=con.preparecall("{?= call sum4(?,?)"); 14. stmt.setint(2,10); 15. stmt.setint(3,43); 16. stmt.registeroutparameter(1,types.integer); 17. stmt.execute(); System.out.println(stmt.getInt(1)); 17. Output: 53 Batch Processing in JDBC Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance fast. The java.sql.statement and java.sql.preparedstatement interfaces provide methods for batch processing. Advantage of Batch Processing Fast Performance Methods of Statement interface The required methods for batch processing are given below: Method Description void addbatch(string query) It adds query into batch. int[] executebatch() It executes the batch of queries. Example of batch processing in jdbc Let's see the simple example of batch processing in jdbc. It follows following steps:

263 Load the driver class Create Connection Create Statement Add query in the batch Execute Batch Close Connection import java.sql.*; class FetchRecords{ public static void main(string args[])throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection m","oracle"); con.setautocommit(false); Statement stmt=con.createstatement(); 9. stmt.addbatch("insert into user420 values(190,'abhi',40000)"); 10. stmt.addbatch("insert into user420 values(191,'umesh',50000)"); stmt.executebatch();//executing the batch con.commit(); 15. con.close(); 16. If you see the table user420, two records has been added. Example of batch processing using PreparedStatement 1. import java.sql.*; 2. import java.io.*; 3. class BP{ 4. public static void main(string args[]){ 5. try{ Class.forName("oracle.jdbc.driver.OracleDriver"); 8. Connection m","oracle"); PreparedStatement ps=con.preparestatement("insert into user420 values(?,?,?)"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 8. while(true){ System.out.println("enter id"); 16. String s1=br.readline(); 17. int id=integer.parseint(s1); System.out.println("enter name");

264 20. String name=br.readline();

265 System.out.println("enter salary"); 23. String s3=br.readline(); 24. int salary=integer.parseint(s3); ps.setint(1,id); 27. ps.setstring(2,name); 28. ps.setint(3,salary); ps.addbatch(); 31. System.out.println("Want to add more records y/n"); 32. String ans=br.readline(); 33. if(ans.equals("n")){ 34. break; ps.executebatch(); System.out.println("record successfully saved"); con.close(); 43. catch(exception e){system.out.println(e); It will add the queries into the batch until user press n. Finally it executes the batch. Thus all the added queries will be fired. JDBC RowSet The instance of RowSet is the java bean component because it has properties and java bean notification mechanism. It is introduced since JDK 5. It is the wrapper of ResultSet. It holds tabular data like ResultSet but it is easy and flexible to use. The implementation classes of RowSet interface are as follows: JdbcRowSet CachedRowSet WebRowSet JoinRowSet FilteredRowSet Let's see how to create and execute RowSet.

266 1. JdbcRowSet rowset = RowSetProvider.newFactory().createJdbcRowSet(); 2. rowset.seturl("jdbc:oracle:thin:@localhost:1521:xe"); 3. rowset.setusername("system"); 4. rowset.setpassword("oracle"); rowset.setcommand("select * from emp400"); 7. rowset.execute(); It is the new way to get the instance of JdbcRowSet since JDK 7. Advantage of RowSet The advantages of using RowSet are given below: 1. It is easy and flexible to use 2. It is Scrollable and Updatable bydefault Simple example of JdbcRowSet Let's see the simple example of JdbcRowSet without event handling code. 1. import java.sql.connection; 2. import java.sql.drivermanager; 3. import java.sql.resultset; 4. import java.sql.statement; 5. import javax.sql.rowsetevent; 6. import javax.sql.rowsetlistener; 7. import javax.sql.rowset.jdbcrowset; 8. import javax.sql.rowset.rowsetprovider; public class RowSetExample { 11. public static void main(string[] args) throws Exception { 12. Class.forName("oracle.jdbc.driver.OracleDriver"); //Creating and Executing RowSet 15. JdbcRowSet rowset = RowSetProvider.newFactory().createJdbcRowSet(); 16. rowset.seturl("jdbc:oracle:thin:@localhost:1521:xe"); 17. rowset.setusername("system"); 18. rowset.setpassword("oracle"); rowset.setcommand("select * from emp400"); 21. rowset.execute(); while (rowset.next()) { 24. // Generating cursor Moved event 25. System.out.println("Id: " + rowset.getstring(1)); 26. System.out.println("Name: " + rowset.getstring(2)); 27. System.out.println("Salary: " + rowset.getstring(3));

267 The output is given below: Id: 55 Name: Om Bhim Salary: Id: 190 Name: abhi Salary: Id: 191 Name: umesh Salary: Full example of Jdbc RowSet with event handling To perform event handling with JdbcRowSet, you need to add the instance ofrowsetlistener in the addrowsetlistener method of JdbcRowSet. The RowSetListener interface provides 3 method that must be implemented. They are as follows: 1) public void cursormoved(rowsetevent event); 2) public void rowchanged(rowsetevent event); 3) public void rowsetchanged(rowsetevent event); Let's write the code to retrieve the data and perform some additional tasks while cursor is moved, cursor is changed or rowset is changed. The event handling operation can't be performed using ResultSet so it is preferred now. 1. import java.sql.connection; 2. import java.sql.drivermanager; 3. import java.sql.resultset; 4. import java.sql.statement; 5. import javax.sql.rowsetevent; 6. import javax.sql.rowsetlistener; 7. import javax.sql.rowset.jdbcrowset; 8. import javax.sql.rowset.rowsetprovider;

268 public class RowSetExample { 11. public static void main(string[] args) throws Exception { 12. Class.forName("oracle.jdbc.driver.OracleDriver"); //Creating and Executing RowSet 15. JdbcRowSet rowset = RowSetProvider.newFactory().createJdbcRowSet(); 16. rowset.seturl("jdbc:oracle:thin:@localhost:1521:xe"); 17. rowset.setusername("system"); 18. rowset.setpassword("oracle"); rowset.setcommand("select * from emp400"); 21. rowset.execute(); //Adding Listener and moving RowSet 24. rowset.addrowsetlistener(new MyListener()); while (rowset.next()) { 27. // Generating cursor Moved event 28. System.out.println("Id: " + rowset.getstring(1)); 29. System.out.println("Name: " + rowset.getstring(2)); 30. System.out.println("Salary: " + rowset.getstring(3)); class MyListener implements RowSetListener { 37. public void cursormoved(rowsetevent event) { 38. System.out.println("Cursor Moved..."); public void rowchanged(rowsetevent event) { 41. System.out.println("Cursor Changed..."); public void rowsetchanged(rowsetevent event) { 44. System.out.println("RowSet changed..."); The output is as follows: Cursor Moved... Id: 55 Name: Om Bhim Salary: Cursor Moved... Id: 190 Name: abhi Salary: 40000

269 Cursor Moved... Id: 191 Name: umesh Salary: Cursor Moved... Jdbc New Features The latest version of JDBC is 4.0 currently. Java has updated jdbc api to ease and simplify the coding to database interactivity. Here, we are going to see the features included in Jdbc 3.0 and Jdbc 4.0. Jdbc 3.0 Features The important features of JDBC API 3.0 are as follows: Jdbc RowSet We have done the great discussion on JdbcRowSet in the previous page. Savepoint in transaction management Now you are able to create, rollback and release the savepoint by Connection.setSavepoint(), Connection.rollback(Savepoint svpt) and Connection.releaseSavepoint(Savepoint svpt) methods. Statement and ResultSet Caching for Connection Pooling Now you are able to reuse the statement and result set because jdbc 3 provides you the facility of statement caching and result set caching. Switching between Global and Local Transactions Retrieval of auto generated keys Now you are able to get the auto generated keys by the method getgeneratedkeys(). Jdbc 4.0 Features The important features of JDBC API 4.0 are given below: Automatic Loading of Driver class You don't need to write Class.forName() now because it is loaded bydefault since jdbc4. Subclasses of SQLException Jdbc 4 provides new subclasses of SQLException class for better readability and handling.

270 New methods There are many new methods introduced in Connection, PreparedStatement, CallableStatement, ResultSet etc. Improved DataSource Now data source implementation is improved. Event Handling support in Statement for Connection Pooling Now Connection Pooling can listen statement error and statement closing events. New Features in Java There are many new features that have been added in java. There are major enhancement made in Java5, Java6 and Java7 like auto-boxing, generics, var-args, java annotations,enum, premain method etc. RMI (Remote Method Invocation) The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM. The RMI provides remote communication between the applications using two objects stub and skeleton. Understanding stub and skeleton RMI uses stub and skeleton object for communication with the remote object. A remote object is an object whose method can be invoked from another JVM. Let's understand the stub and skeleton objects: stub The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It resides at the client side and represents the remote object. When the caller invokes method on the stub object, it does the following tasks: 1. It initiates a connection with remote Virtual Machine (JVM), 2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM), 3. It waits for the result 4. It reads (unmarshals) the return value or exception, and

271 5. It finally, returns the value to the caller. skeleton The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed through it. When the skeleton receives the incoming request, it does the following tasks: 1. It reads the parameter for the remote method 2. It invokes the method on the actual remote object, and 3. It writes and transmits (marshals) the result to the caller. In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons. Understanding requirements for the distributed applications If any application performs these tasks, it can be distributed application.. 1. The application need to locate the remote method 2. It need to provide the communication with the remote objects, and 3. The application need to load the class definitions for the objects.

272 The RMI application have all these features, so it is called the distributed application. Steps to write the RMI program The is given the 6 steps to write the RMI program. 1. Create the remote interface 2. Provide the implementation of the remote interface 3. Compile the implementation class and create the stub and skeleton objects using the rmic tool 4. Start the registry service by rmiregistry tool 5. Create and start the remote application 6. Create and start the client application RMI Example In this example, we have followed all the 6 steps to create and run the rmi application. The client application need only two files, remote interface and client application. In the rmi application, both client and server interacts with the remote interface. The client application invokes methods on the proxy object, RMI sends the request to the remote JVM. The return value is sent back to the proxy object and then to the client application.

273 1) create the remote interface For creating the remote interface, extend the Remote interface and declare the RemoteException with all the methods of the remote interface. Here, we are creating a remote interface that extends the Remote interface. There is only one method named add() and it declares RemoteException. 1. import java.rmi.*; 2. public interface Adder extends Remote{ 3. public int add(int x,int y)throws RemoteException; 4. 2) Provide the implementation of the remote interface Now provide the implementation of the remote interface. For providing the implementation of the Remote interface, we need to Either extend the UnicastRemoteObject class, or use the exportobject() method of the UnicastRemoteObject class In case, you extend the UnicastRemoteObject class, you must define a constructor that declares RemoteException.

274 1. import java.rmi.*; 2. import java.rmi.server.*; 3. public class AdderRemote extends UnicastRemoteObject implements Adder{ 4. AdderRemote()throws RemoteException{ 5. super(); public int add(int x,int y){return x+y; 8. 3) create the stub and skeleton objects using the rmic tool. Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the RMI compiler and creates stub and skeleton objects. 1. rmic AdderRemote 4) Start the registry service by the rmiregistry tool Now start the registry service by using the rmiregistry tool. If you don't specify the port number, it uses a default port number. In this example, we are using the port number rmiregistry ) Create and run the server application Now rmi services need to be hosted in a server process. The Naming class provides methods to get and store the remote object. The Naming class provides 5 methods. 1. public static java.rmi.remote lookup(java.lang.string) throws java.rmi.notboundexception, java.net.malformedurlexception, java.rmi.remoteexception; it returns the reference of the remote object. 2. public static void bind(java.lang.string, java.rmi.remote) throws java.rmi.alreadyboundexception, java.net.malformedurlexception, java.rmi.remoteexception; it binds the remote object with the given name. 3. public static void unbind(java.lang.string) throws java.rmi.remoteexception, java.rmi.notboundexception, java.net.malformedurlexception; it destroys the remote object which is bound with the given name. 4. public static void rebind(java.lang.string, java.rmi.remote) throws java.rmi.remoteexception, java.net.malformedurlexception; it binds the remote object to the new name.

275 5. public static java.lang.string[] list(java.lang.string) throws java.rmi.remoteexception, java.net.malformedurlexception; it returns an array of the names of the remote objects bound in the registry. In this example, we are binding the remote object by the name sonoo. 1. import java.rmi.*; 2. import java.rmi.registry.*; 3. public class MyServer{ 4. public static void main(string args[]){ 5. try{ 6. Adder stub=new AdderRemote(); 7. Naming.rebind("rmi://localhost:5000/sonoo",stub); 8. catch(exception e){system.out.println(e); ) Create and run the client application At the client we are getting the stub object by the lookup() method of the Naming class and invoking the method on this object. In this example, we are running the server and client applications, in the same machine so we are using localhost. If you want to access the remote object from another machine, change the localhost to the host name (or IP address) where the remote object is located. 1. import java.rmi.*; 2. public class MyClient{ 3. public static void main(string args[]){ 4. try{ 5. Adder stub=(adder)naming.lookup("rmi://localhost:5000/sonoo"); 6. System.out.println(stub.add(34,4)); 7. catch(exception e){ For running this rmi example, ) compile all the java files javac *.java )create stub and skeleton object by rmic tool rmic AdderRemote )start rmi registry in one command prompt 12.

276 13. rmiregistry )start the server in another command prompt java MyServer )start the client application in another command prompt java MyClient Output of this RMI example

277 Meaningful example of RMI application with database Consider a scenario, there are two applications running in different machines. Let's say MachineA and MachineB, machinea is located in United States and MachineB in India. MachineB want to get list of all the customers of MachineA application. Let's develop the RMI application by following the steps. 1) Create the table First of all, we need to create the table in the database. Here, we are using Oracle10 database.

278 2) Create Customer class and Remote interface File: Customer.java 1. package com.javatpoint; 2. public class Customer implements java.io.serializable{ 3. private int acc_no; 4. private String firstname,lastname, ; 5. private float amount; 6. //getters and setters 7. Note: Customer class must be Serializable. File: Bank.java 1. package com.javatpoint; 2. import java.rmi.*; 3. import java.util.*; 4. interface Bank extends Remote{ 5. public List<Customer> getcustomers()throws RemoteException; 6. 3) Create the class that provides the implementation of Remote interface File: BankImpl.java 1. package com.javatpoint; 2. import java.rmi.*; 3. import java.rmi.server.*; 4. import java.sql.*; 5. import java.util.*;

279 6. class BankImpl extends UnicastRemoteObject implements Bank{ 7. BankImpl()throws RemoteException{ public List<Customer> getcustomers(){ 10. List<Customer> list=new ArrayList<Customer>(); 11. try{ 12. Class.forName("oracle.jdbc.driver.OracleDriver"); 13. Connection m","oracle"); 14. PreparedStatement ps=con.preparestatement("select * from customer400"); 15. ResultSet rs=ps.executequery(); while(rs.next()){ 18. Customer c=new Customer(); 19. c.setacc_no(rs.getint(1)); 20. c.setfirstname(rs.getstring(2)); 21. c.setlastname(rs.getstring(3)); 22. c.set (rs.getstring(4)); 23. c.setamount(rs.getfloat(5)); 24. list.add(c); con.close(); 28. catch(exception e){system.out.println(e); 29. return list; 30. //end of getcustomers() 31. 4) Compile the class rmic tool and start the registry service by rmiregistry tool

280 5) Create and run the Server File: MyServer.java 1. package com.javatpoint; 2. import java.rmi.*; 3. public class MyServer{ 4. public static void main(string args[])throws Exception{ 5. Remote r=new BankImpl(); 6. Naming.rebind("rmi://localhost:6666/javatpoint",r); 7. 6) Create and run the Client File: MyClient.java 1. package com.javatpoint; 2. import java.util.*; 3. import java.rmi.*; 4. public class MyClient{ 5. public static void main(string args[])throws Exception{ 6. Bank b=(bank)naming.lookup("rmi://localhost:6666/javatpoint"); List<Customer> list=b.getcustomers(); 9. for(customer c:list){ 10. System.out.println(c.getAcc_no()+" "+c.getfirstname()+" "+c.getlastname() 11. +" "+c.get ()+" "+c.getamount());

281

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

Java Basic Datatypees

Java Basic Datatypees Basic Datatypees Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory. Based on the data type of a variable,

More information

You must declare all variables before they can be used. Following is the basic form of a variable declaration:

You must declare all variables before they can be used. Following is the basic form of a variable declaration: Variable Types A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the

More information

The Java language has a wide variety of modifiers, including the following:

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

Following is the general form of a typical decision making structure found in most of the programming languages:

Following is the general form of a typical decision making structure found in most of the programming languages: Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined

More information

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: PART 4 Variable Types In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: type identifier [ = value][, identifier [= value]...] ; To

More information

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Preview from Notesale.co.uk Page 9 of 108

Preview from Notesale.co.uk Page 9 of 108 The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break byte case catch char class

More information

1. History of Java. The Green project engineers used a virtual machine as well, so this solved their main problem.

1. History of Java. The Green project engineers used a virtual machine as well, so this solved their main problem. 1. History of Java Lecture1 Java goes back to 1991, when a group of Sun engineers, led by Patrick Naughton and SunFellow (and all-around computer wizard) James Gosling, wanted to design a small computer

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Basic Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

Answer1. Features of Java

Answer1. Features of Java Govt Engineering College Ajmer, Rajasthan Mid Term I (2017-18) Subject: PJ Class: 6 th Sem(IT) M.M:10 Time: 1 hr Q1) Explain the features of java and how java is different from C++. [2] Q2) Explain operators

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Java Programming. Theory Manual

Java Programming. Theory Manual Java Programming Theory Manual Dr. S.N. Mishra Head of Department Computer Science Engineering and Application IGIT Sarang Ramesh kumar Sahoo Asst. Prof. Dept. of CSEA IGIT Sarang CHAPTER 1 INTRODUCTION

More information

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS Java language Part 1. Java fundamentals Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua What Java is? Programming language Platform: Hardware Software OS: Windows, Linux, Solaris,

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT.

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT. NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT. Object and Classes Data Abstraction and Encapsulation Inheritance Polymorphism Dynamic Binding Message Communication Objects are the basic runtime entities in

More information

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators, Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators, Expressions, Statements and Arrays. Java technology is: A programming

More information

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

More information

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials Introduction to Android Saturday Yanqiao ZHU Google Camp School of Software Engineering, Tongji University In courtesy of The Java Tutorials Getting Started Introduction to Java The Java Programming Language

More information

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M. Java Language Essentials Java is Case Sensitive All Keywords are lower case White space characters are ignored Spaces, tabs, new lines Java statements must end with a semicolon ; Compound statements use

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Language Fundamentals Summary

Language Fundamentals Summary Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt, Michael Skusa Software Systems Institute Object-oriented Analysis and Design 1999/2000 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Chapter 1 Introduction to Java

Chapter 1 Introduction to Java What is Java? Chapter 1 Introduction to Java Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows,

More information

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Programming. Syntax and Semantics

Programming. Syntax and Semantics Programming For the next ten weeks you will learn basic programming principles There is much more to programming than knowing a programming language When programming you need to use a tool, in this case

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Java Notes. 10th ICSE. Saravanan Ganesh

Java Notes. 10th ICSE. Saravanan Ganesh Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses

More information

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

Lecture 1: Overview of Java

Lecture 1: Overview of Java Lecture 1: Overview of Java What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups: JAVA BASIC OPERATORS http://www.tuto rialspo int.co m/java/java_basic_o perato rs.htm Copyrig ht tutorialspoint.com Java provides a rich set of operators to manipulate variables. We can divide all the

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

Software Practice 1 Basic Grammar

Software Practice 1 Basic Grammar Software Practice 1 Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee (43) 1 2 Java Program //package details

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

A variable is a name that represents a value. For

A variable is a name that represents a value. For DECLARE A VARIABLE A variable is a name that represents a value. For example, you could have the variable myage represent the value 29. Variables can be used to perform many types of calculations. Before

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Data Types, Literals, Operators

Data Types, Literals, Operators Data Types, Literals, Operators Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Certified Core Java Developer VS-1036

Certified Core Java Developer VS-1036 VS-1036 1. LANGUAGE FUNDAMENTALS The Java language's programming paradigm is implementation and improvement of Object Oriented Programming (OOP) concepts. The Java language has its own rules, syntax, structure

More information

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1 CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Winter 2008 3/11/2008 2002-08 Hal Perkins & UW CSE V-1 Agenda Java virtual machine architecture.class files Class loading Execution engines

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

Core Java Syllabus. Overview

Core Java Syllabus. Overview Core Java Syllabus Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

CompSci 125 Lecture 02

CompSci 125 Lecture 02 Assignments CompSci 125 Lecture 02 Java and Java Programming with Eclipse! Homework:! http://coen.boisestate.edu/jconrad/compsci-125-homework! hw1 due Jan 28 (MW), 29 (TuTh)! Programming:! http://coen.boisestate.edu/jconrad/cs125-programming-assignments!

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

CHAPTER 2 Java Fundamentals

CHAPTER 2 Java Fundamentals CHAPTER 2 Java Fundamentals Copyright 2016 Pearson Education, Inc., Hoboken NJ Chapter Topics Chapter 2 discusses the following main topics: The Parts of a Java Program The print and println Methods, and

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Special Topics: Programming Languages

Special Topics: Programming Languages Lecture #23 0 V22.0490.001 Special Topics: Programming Languages B. Mishra New York University. Lecture # 23 Lecture #23 1 Slide 1 Java: History Spring 1990 April 1991: Naughton, Gosling and Sheridan (

More information

IQTIDAR ALI Lecturer IBMS Agriculture University Peshawar

IQTIDAR ALI Lecturer IBMS Agriculture University Peshawar IQTIDAR ALI Lecturer IBMS Agriculture University Peshawar Upon completing the course, you will understand Create, compile, and run Java programs Primitive data types Java control flow Operator Methods

More information

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java Introduction Objectives An overview of object-oriented concepts. Programming and programming languages An introduction to Java 1-2 Problem Solving The purpose of writing a program is to solve a problem

More information

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Hwansoo Han T.A. Minseop Jeong T.A. Wonseok Choi 1 Java Program //package details public class ClassName {

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Java Programming. Atul Prakash

Java Programming. Atul Prakash Java Programming Atul Prakash Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier

More information

Java: framework overview and in-the-small features

Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide Module 3 Identifiers, Keywords, and Types Objectives Upon completion of this module, you should be able to: Use comments in a source program Distinguish between valid and invalid identifiers Recognize

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

4 Programming Fundamentals. Introduction to Programming 1 1

4 Programming Fundamentals. Introduction to Programming 1 1 4 Programming Fundamentals Introduction to Programming 1 1 Objectives At the end of the lesson, the student should be able to: Identify the basic parts of a Java program Differentiate among Java literals,

More information

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Chettinad College of Engineering & Technology/II-MCA/ MC9235 Web Programming WEB PROGRAMMING DEPARTMENT OF MCA

Chettinad College of Engineering & Technology/II-MCA/ MC9235 Web Programming WEB PROGRAMMING DEPARTMENT OF MCA WEB PROGRAMMING DEPARTMENT OF MCA Class II MCA Semester III Batch & Year B4 & 2012 Staff A.SALEEM RAJA, MCA.,M.Phil.,M.Tech Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 1 UNIT III JAVA FUNDAMENTALS Java

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one. http://www.tutorialspoint.com/go/go_operators.htm GO - OPERATORS Copyright tutorialspoint.com An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information