Programming in Learning objectives

After undergoing the subject, students will be able to Understand the history of Java. Explain how Java programs are compiled, interpreted and executed in java environment. Explain how Java is used to develop different types of application Explain the concept of Packages and their uses Explain the concept of multithreading. Explain how we can build application with JDK.

1. History of Java

Java Programming Language was written by along with two other person ‘Mike Sheridan‘ and ‘Patrick Naughton‘, while they were working at . Initially it was named oak Programming Language.

1.1.Releases of Java

Initial Java Versions 1.0 and 1.1 was released in the year 1996 for Linux, Solaris, Mac and Windows. Java version 1.2 (Commonly called as java 2) was released in the year 1998. Java Version 1.3 codename Kestrel was released in the year 2000. Java Version 1.4 codename Merlin was released in the year 2002. Java Version 1.5/Java SE 5 codename ‘Tiger’ was released in the year 2004. Java Version 1.6/Java SE 6 Codename ‘Mustang’ was released in the year 2006. Java Version 1.7/Java SE 7 Codename ‘Dolphin’ was released in the year 2011. Java Version 1.8 is the current stable release which was released this year (2015).

1.2. Five Goals which were taken into consideration while developing Java:

Keep it simple, familiar and object oriented. Keep it Robust and Secure. Keep it architecture-neural and portable. Executable with High Performance. Interpreted, threaded and dynamic.

2.

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which can be executed. JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent)

2.1. What is JVM It is: 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 Oracle and other companies. An implementation Its implementation is known as JRE (Java Runtime Environment). Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.

2.2. 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.

3. JIT Compiler

The key of java power "Write once, run everywhere" is bytecode. The way bytecodes get converted to the appropriate native instructions for an application has a huge impact on the speed of an application. These bytecode can be interpreted, compiled to native code or directly executed on a processor whose Instruction Set Architecture is the bytecode specification. Interpreting the bytecode which is the standard implementation of the Java Virtual Machine (JVM) makes execution of programs slow. To improve performance, JIT compilers interact with the JVM at run time and compile appropriate bytecode sequences into native machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to having the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a relatively lengthy translation process. This can lead to performance gains in the execution speed, unless methods are executed less frequently. The time that a JIT compiler takes to compile the bytecode is added to the overall execution time, and could lead to a higher execution time than an interpreter for executing the bytecode if the methods that are compiled by the JIT are not invoked frequently. The JIT compiler performs certain optimizations when compiling the bytecode to native code. Since the JIT compiler translates a series of bytecode into native instructions, it can perform some simple optimizations. Some of the common optimizations performed by JIT compilers are data-analysis, translation from stack operations to register operations, reduction of memory accesses by register allocation, elimination of common sub-expressions etc. The higher the degree of optimization done by a JIT compiler, the more time it spends in the execution stage. Therefore a JIT compiler cannot afford to do all the optimizations that is done by a static compiler, both because of the overhead added to the execution time and because it has only a restricted view of the program.

3.1. How it works The Just-In-Time (JIT) compiler is a component of the Java Runtime Environment that improves the performance of Java applications at run time. Java programs consists of classes, which contain platform neutral bytecode that can be interpreted by a JVM on many different computer architectures. At run time, the JVM loads the class files, determines the semantics of each individual bytecode, and performs the appropriate computation. The additional processor and memory usage during interpretation means that a Java application performs more slowly than a native application. The JIT compiler helps improve the performance of Java programs by compiling bytecode into native machine code at run time.

The JIT compiler is enabled by default, and is activated when a Java method is called. The JIT compiler compiles the bytecode of that method into native machine code, compiling it "just in time" to run. When a method has been compiled, the JVM calls the compiled code of that method directly instead of interpreting it. Theoretically, if compilation did not require processor time and memory usage, compiling every method could allow the speed of the Java program to approach that of a native application. JIT compilation does require processor time and memory usage. When the JVM first starts up, thousands of methods are called. Compiling all of these methods can significantly affect startup time, even if the program eventually achieves very good peak performance.

4. Java Features

4.1. General Purpose Java capabilities are not limited to any specific application domain rather it can be used in various application domain and hence it is called General Purpose Programming Language.

4.2. Class based Java is a class based/oriented programming language which means Java supports inheritance feature of object-oriented Programming Language.

4.3. Object oriented Java is object-oriented means software developed in Java are combination of different types of object.

4.5. Platform Independent A Java code will run on any JVM (Java Virtual Machine). Literally you can run same Java code on Windows JVM, Linux JVM, Mac JVM or any other JVM practically and get same result every time.

4.6. Architectural neutral A Java code is not dependent upon Processor Architecture. A Java Application compiled on 64 bit architecture of any platform will run on 32 bit (or any other architecture) system without any issue.

4.7. Multithreaded A thread in Java refers to an independent program. Java supports multithread which means Java is capable of running many tasks simultaneously, sharing the same memory.

4.8. .Dynamic Java is a Dynamic programming language which means it executes many programming behavior at Runtime and don’t need to be passed at compile time as in the case of static programming.

4.9. Distributed Java Supports distributed System which means we can access files over Internet just by calling the methods.

4.10. Portable A Java program when compiled produce bytecodes. Bytecodes are magic. These bytecodes can be transferred via network and can be executed by any JVM, hence came the concept of ‘Write once, Run Anywhere(WORA)’.

4.11. Robust Java is a robust programming Language which means it can cope with error while the program is executing as well as keep operating with abnormalities to certain extent. Automatic Garbage collection, strong memory management, exception handling and type checking further adds to the list.

4.12. Interpreted Java is a compiled programming Language which compiles the Java program into Java byte codes. This JVM is then interpreted to run the program.

4.13. Security Unlike other programming Language where Program interacts with OS using User runtime environment of OS, Java provides an extra layer of security by putting JVM between Program and OS.

4.14. Simple Syntax Java is an improved ++ which ensures friendly syntax but with removed unwanted features and inclusion of Automatic Garbage collection.

4.15. High Level Programming Language Java is a High Level Programming Language the syntax of which is human readable. Java lets programmer to concentrate on what to achieve and not how to achieve. The JVM converts a Java Program to Machine understandable language.

4.16. High Performance Java make use of Just-In-Time compiler for high performance. Just-In-Time compiler is a computer program that turns Java byte codes into instructions that can directly be sent to compilers.

5. Native Code

Native code is computer programming (code) that is compiled to run with a particular processor (such as an Intel x86-class processor) and its set of instructions. If the same program is run on a computer with a different processor, software can be provided so that the computer emlates the original processor. In this case, the original program runs in "emulation mode" on the new processor and almost certainly more slowly than in native mode on the original processor. (The program can be rewritten and recompiled so that it runs on the new processor in native mode.) Native code can also be distinguished from bytecode (sometimes called interpreted code), a form of code that can be said to run in a virtual machine (for example, the Java Virtual Machine). The virtual machine is a program that converts the platform-generalized bytecode into the native code that will run in a specific processor. Microsoft's .NET compilers for its Visual Basic, C#, and JavaScript languages produce bytecode (which Microsoft calls Intermediate Language). Java bytecode and Microsoft's Intermediate Language can be compiled into native code before execution by a just-in-time compiler for faster performance.

6. Java application types

6.1. Desktop GUI Applications: Java provides GUI development through various means like Abstract Windowing Toolkit (AWT), Swing and JavaFX. While AWT contains a number of pre-constructed components such as menu, button, list, and numerous third-party components, Swing, a GUI widget toolkit, additionally provides certain advanced components like trees, tables, scroll panes, tabbed panel and lists. JavaFX, a set of graphics and media packages, provides Swing interoperability, 3D graphic features and self-contained deployment model which facilitates quick scripting of Java applets and applications.

6.2. Mobile Applications: Java Platform, Micro Edition (Java ME or J2ME) is a cross-platform framework to build applications that run across all Java supported devices, including feature phones and smart phones. Further, applications for Android, one of the most popular mobile operating systems, are usually scripted in Java using the Android Software Development Kit (SDK) or other environments.

6.3. Embedded Systems: Embedded systems, ranging from tiny chips to specialized computers, are components of larger electromechanical systems performing dedicated tasks. Several devices, such as SIM cards, blue- ray disk players, utility meters and televisions, use embedded Java technologies. According to Oracle, 100% of Blu-ray Disc Players and 125 million TV devices employ Java.

6.4. Web Applications: Java provides support for web applications through Servlets, Struts or JSPs. The easy programming and higher security offered by the programming language has allowed a large number of government applications for health, social security, education and insurance to be based on Java. Java also finds application in development of eCommerce web applications using open-source eCommerce platforms, such as Broadleaf.

6.5. Web Servers and Application Servers: The Java ecosystem today contains multiple Java web servers and application servers. While , Simple, Jo!, Rimfaxe Web Server (RWS) and Project Jigsaw dominate the web server space, WebLogic, WebSphere, and Jboss EAP dominate commercial application server space.

6.6. Enterprise Applications: Java Enterprise Edition (Java EE) is a popular platform that provides API and runtime environment for scripting and running enterprise software, including network applications and web-services. Oracle claims Java is running in 97% of enterprise computers. The higher performance guarantee and faster computing in Java has resulted in high frequency trading systems like Murex to be scripted in the language. It is also the backbone for a variety of banking applications which have Java running from front user end to back server end.

6.7. Scientific Applications: Java is the choice of many software developers for writing applications involving scientific calculations and mathematical operations. These programs are generally considered to be fast and secure, have a higher degree of portability and low maintenance. Applications like MATLAB use Java both for interacting user interface and as part of the core system.

7. Comparision of java with c++

7.1. c++

1. C++ is platform-dependent. 2. C++ is mainly used for system programming. 3. C++ was designed for systems and applications programming. It was an extension of C programming language. 4. C++ supports the goto statement. 5. C++ supports multiple inheritance. 6. C++ supports operator overloading. 7. C++ supports operator overloading. 8. C++ uses compiler only. C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependent. 9. C++ supports both call by value and call by reference. 10. C++ supports structures and unions. 11. C++ doesn't have built-in support for threads. It relies on third-party libraries for thread support. 12. C++ supports virtual keyword so that we can decide whether or not override a function.

7.2. Java

1. Java is platform-independent. 2. Java is mainly used for application programming. It is widely used in window, web-based, enterprise and mobile applications. 3. Java was designed and created as an interpreter for printing systems but later extended as a support network computing. It was designed with a goal of being easy to use and accessible to a broader audience. 4. Java doesn't support the goto statement. 5. Java doesn't support multiple inheritance through class. It can be achieved by interfaces in java. 6. Java doesn't support operator overloading. 7. Java supports pointer internally. However, you can't write the pointer program in java. It means java has restricted pointer support in java. 8. Java uses compiler and interpreter both. Java source code is converted into bytecode at compilation time. The interpreter executes this bytecode at runtime and produces output. Java is interpreted that is why it is platform independent. 9. Java supports call by value only. There is no call by reference in java. 10. Java doesn't support structures and unions. 11. Java has built-in thread support. 12. Java supports documentation comment (/** ... */) to create documentation for java source code. 13. Java has no virtual keyword. We can override all non-static methods by default. In other words, non-static methods are virtual by default.

Multiple choice Questions

1. Java is ---- language? a. object oriented b. procedure oriented 2. Who developed Java? a. Dennis Ritchie b. James Gosling 3. What is JDK? a. b. Java Designer Kit 4. What is JVM? a. Java Virtual Machine b. Java Virtual Memory 5. What do you mean by JIT? a. Java In Time b. Just In Time

Short Answer Type Question 1. Write History of java 2. How java is different from c? 3. Explain main features of Java. 4. How Java works? 5. What is JVM, what are the tasks of JVM? 6. What is native code?

Long Answer Type question Questions 1. Explain how java is a platform neutral language with diagram. 2. Explain how Java is different from C and C++. 3. Explain features of Java in detail.

Exception Handling in Java

1. Exception Handling

1.1 Exceptions

Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.). In Java, an exception is an object that wraps an error event that occurred within a method and contains information about the error and its types.

1.2 Exception Handling

The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so that normal flow of the application can be maintained. In this page, we will learn about Java exceptions, its type and the difference between checked and unchecked exceptions.

2. Java Exception Handling Keywords

Java provides specific keywords for exception handling purposes, we will look after them first and then we will write a simple program showing how to use them for exception handling.

2.1. throw

We know that if any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it.

2.2. throws

When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

2.3. try-catch

We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception. Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch try { //code that may throw exception } catch (Exception_class_Name ref){} Syntax of try-finally block try{ //code that may throw exception } finally {}

2.4. .finally – finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.

Let’s see a simple programming showing exception handling in java. package com.journaldev.exceptions; import java.io.FileNotFoundException; import java.io.IOException; public class ExceptionHandling {

public static void main(String[] args) throws FileNotFoundException, IOException { try{ testException(-5); testException(-10); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }finally{ System.out.println("Releasing resources"); } testException(15); }

public static void testException(int i) throws FileNotFoundException, IOException{ if(i < 0){ FileNotFoundException myException = new FileNotFoundException("Negative Integer "+i); throw myException; }else if(i > 10){ throw new IOException("Only supported for index 0 to 10"); }

}

} Output of above program is:

java.io.FileNotFoundException: Negative Integer -5 at com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:24) at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:10) Releasing resources Exception in thread "main" java.io.IOException: Only supported for index 0 to 10 at com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:27) at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:19) Notice that testException() method is throwing exception using throw keyword and method signature uses throws keyword to let caller know the type of exceptions it might throw. In main() method, I am handling exception using try-catch block in main() method and when I am not handling it, I am propagating it to runtime with throws clause in main method. Notice that testException(-10) never gets executed because of exception and then execution of finally block after try-catch block is executed. The printStackTrace() is one of the useful method in Exception class and used for debugging purpose.

 We can’t have catch or finally clause without a try statement.  A try statement should have either catch block or finally block, it can have both blocks.  We can’t write any code between try-catch-finally block.  We can have multiple catch blocks with a single try statement.  try-catch blocks can be nested similar to if-else statements.  We can have only one finally block with a try-catch statement.

3. Java Exception Hierarchy

As stated earlier, when any exception is raised an exception object is getting created. Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.

3.1.Errors: Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error. That’s why we have a separate hierarchy of errors and we should not try to handle these situations. Some of the common Errors are OutOfMemoryError and StackOverflowError.

3.2.Checked Exception Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException.

3. Difference between throw and throws in Java

No. Throw throws

1) Java throw keyword is used to explicitly throw an Java throws keyword is used to declare an exception. exception.

2) Checked exception cannot be propagated using throw Checked exception can be propagated with throws. only.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g. public void method()throws IOException,SQLException.

4. Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:

No. Final finally finalize

1) Final is used to apply restrictions on class, Finally is used to place Finalize is used to perform method and variable. Final class can't be important code, it will be clean up processing just inherited, final method can't be overridden executed whether exception before object is garbage and final variable value can't be changed. is handled or not. collected.

2) Final is a keyword. Finally is a block. Finalize is a method.

Multiple choice questions

1. Which of the following is used for deallocating memory space? a. final b. finally c. finalize 2. Which of the following is used to explicitly throw an exception? a. throw b. throws 3. Which of the following is a block? a. Finally b. final

Short answer questions

1. What is an exception? 2. What is an error? 3. What is Try Block or Catch Block? 4. What is Finally Block? 5. Explain the types of exception. 6. What is the difference between throw and throws keywords. 7. How to throw an exception 8. Explain the syntax of exception handling with example. 9. What is the difference between error and exception in Java?

Long answer questions

1. What is exception handling and what are various methods used in it explain?