Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java: An introduction.

Similar presentations


Presentation on theme: "Java: An introduction."— Presentation transcript:

1 Java: An introduction

2 Java Language Java was created by a team of members called "Green" led by James Arthur Gosling. When Java was created in 1991, it was originally called Oak. It is a free and open source software (FOSS) under GNU General Public License(GPL) First version of Java was released in 1995. Java is an Object oriented language, simple, portable, platform independent, robust and secure. We will be focusing on Java 1.6. A group of engineers from Sun Microsystems, now acquired by Oracle Corporation, led by James Gosling created Java. It was released in The Language was originally called Oak (in 1991) after the Oak tree that could be seen in Gosling's office. They later found that Oak was a name already taken. So, popular story goes that after many hours of trying to come up with a new name, the development team went out for coffee and the name Java was born! FOSS (GPL): FOSS is a free and open source software and GNU General Public License The GNU General Public License is a free, copy-left license for software and other kinds of works Copyleft is used to describe the practice of using copyright law to offer the right to distribute copies and modified versions of a work and requiring that the same rights be preserved in modified versions of the work

3 Flavors Of Java JSE Java Standard Edition formerly known as J2SE.
This forms the core part of Java language. JEE Java Enterprise Edition formerly known as J2EE. These are the set of packages that are used to develop distributed enterprise-scale applications. These applications are deployed on JEE application servers. JME Java Micro Edition formerly known as J2ME. These are the set of packages used to develop application for mobile devices and embedded systems. Java also comes in several versions: JDK 1.0 (1995) JDK 1.1 (1997) J2SE 1.2 (1998) ) Playground J2SE 1.3 (2000)  Kestrel J2SE 1.4 (2002)  Merlin The above 3 was called Java 2 J2SE 5.0 (2004)  Tiger Java SE 6 ( 2006)  Mustang Java SE 7 (2011) Dolphin Our focus

4 Simple Hello World in Java
Hello.java public class Hello{ public static void main(String args[]) { System.out.println(“Hello World!”); }} Special statement used to display data on console. ‘println’ causes the next print statement to be printed in the next line. System.out.print prints in the same line. main() is a method from where program execution begins.

5 Environment to compile and execute
Compile java programs From command prompt Through an IDE (Integrated development environment) Eclipse Apache NetBeans Oracle SDN JBuilder  Borland Integrated Development Environment  IBM What is an IDE?

6 Setup JDK or find appropriate link in Download Java based on the type of OS Windows Linux Mac OS Solaris Install JDK

7 JDK installation directory
Java Runtime Environment Java virtual machine rt.jar is a library file that has all predefined Java classes that are part of core Java. Jar is java archive. Java Executables Java Predefined Classes like String, Date, Math etc.

8 Compilation & execution: command prompt
Save the file as Hello.java. A public class must be saved in the same name as class name. Compile C:\MyJava>javac Hello.java Byte code Hello.class javac Hello.java compilation Source code execution java javac [ options ] [ sourcefiles ] sourcefiles can also include relative or absolute path components –d directory Set the destination directory for class files. D:\ javac –d bin Test.java places Test.class in D:\bin folder. Please note that the bin folder exist before giving this command -nowarn Disable warning messages. -version Displays the version used for compilation -target Generate class files for specific VM version Platform specific code Execute C:\MyJava>java Hello

9 JRE and bytecode Java Bytecode is produced when Java programs are compiled. To execute Java program, JRE must be installed in the system JRE or Java Runtime environment contains Java Virtual Machine Standard class libraries (APIs) Java Plug-in Java Webstart JRE gets installed automatically when JDK is installed. JRE can be installed independent of JDK as well. This will mean that Java programs can be executed in that system.

10 Introducing Eclipse Helios 3.6 IDE
IDE is where the Java programs are written, compiled and executed. Eclipse is an open source project Launched in November 2001 Designed to help developers with specific development tasks GUI and non-GUI application development support Easy integration of tools Supported by multiple operating systems like Windows, Mac, Linux, Solaris, IBM AIX and HP-UX.

11 Eclipse as an IDE Java Development Tooling (JDT) is used for building Java code Provides set of workbench plug-ins for manipulating Java code Java projects, packages, classes, methods, .... Java compiler is built in Used for compiling Java code Creates errors (special markers of code) if compilation fails Numerous content types support Java, HTML, C, XML, ...

12 Activity: Installing Eclipse
Download Eclipse’s Install Zip File from Click on the Download from the main page on Choose the best site from which to download Choose the latest build for download Choose the platform for download and type of download (http or ftp) Specify the location to save the downloaded file. If Java is not installed then we need to download JVM. Fix missing a Java VM? … Download the latest Java Runtime Environment (JRE), e.g., v1.5.0_03 from Click on the downloaded EXE file to install When given the option by the installer, identify a directory of your choice for the install files There are two ways of specifying JVM for Eclipse: By installing JVM under the \jre\ directory off the eclipse install directory By specifying existing JVM in the PATH environment variable Unzip the downloaded file to the directory of your choice

13 Activity: Specifying Workspace
By double-clicking on the eclipse.exe file, the workspace launcher will pop up. The workspace is a place where the user defined data – projects and resources such as folders and files are stored. Always when eclipse is launched, it prompts for a workspace location to open with. This prompt could be turned off or on as per the user’s choice.

14 When Eclipse is run, a Welcome page opens

15 Running Different Workspace
It is possible to run different workspaces using command prompt -data argument must be used with eclipse.exe Workspace location must be specified Useful for grouping project specific data Multiple workspaces can run at the same time Please refer to Eclipse Shortcuts provided in the reference material while using Eclipse

16 UI Overview Closing the Welcome page gets you to the Eclipse workbench user interface The workbench is a collection of windows. Each window contains a menu bar, a toolbar, a shortcut bar and one or more perspectives. A perspective is a visual container for a set of views and content editors. The views exist wholly within the perspective and are not shared, but any opened content editors are shared across perspectives. The objects are stored as regular files within the Eclipse workspace. The workspace consists of one or more top level projects. Each project contains a collection of folders and files.

17 Activity : Create and Execute a Java project
Writing a simple HelloWorld program in Java using Eclipse. Step 1: Start Eclipse. Step 2: Create a new workspace called sample and select Ok. Step 3: Close the Welcome page Step 4: FileNew  Project

18 Step 5: Select "Java" in the category list.
Step 6: Select "Java Project" in the project list. Click "Next". Step 7: Enter a project name into the Project name field, for example, "Hello World Project". Click "Finish" It will ask you if you want the Java perspective to open. Select Yes.

19 Step 8: Select New  Class option
Step 9: Specify the class name “HelloWorld” and select "public static void main(String[] args)" check box. Click Finish. Step 10: In the main method enter the following line. System.out.println("Hello World"); Save it.

20 Step 11: Select Run  Run.

21 Exercise Write a java program to display the following * * * * * *
* * * * * * Use print and println statements. The class file of this program should be automatically placed inside “Design” folder while compiling. Display the version used for compiling. ( 15 mins)

22 Features of Java Language
Simple Object oriented language Portable and platform independent Robust Multithreaded Dynamic Linking Secure Performance Simple: Syntax similar to C/C++,Same types of loops ,Same data types , no pointers, no array index out of bounds problems, no explicit memory allocation & de-allocation. Java is able to overcome memory related problems by the virtue of Garbage collection which is a tool that attempts to free unreferenced memory (memory occupied by objects that are no longer in use by the program) also called garbage, in program Object oriented language: Java is an object oriented language. Every Java application begins with a class. There are no stand-alone functions or global variables in Java. Functions and methods are part of Java Class. Even the main method is part of a java class. Portable and platform independent: discussed in next slides Robust: Strong Error handling mechanism: Lot of checks are done at the compilation itself. More checks are performed at runtime system to make sure that code does not malfunction. Automatic garbage collection. Thread:At the OS level, smallest unit of work that can be scheduled, is a thread. Thread is a sequence of execution of code. A process consists of one or more threads. Multiple threads in the same program share same resources. Unlike a multiple process, multiple threads in a process share same memory location. That is why threads are called Light weight process. Java Standard API has rich set of classes that allows us to work with multiple threads simultaneously Dynamic Linking: The Java class loader(a represented by a class called ClassLoader) is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. It links classes with the executing code. Usually classes are only loaded on demand meaning that only the classes specified in the code are loaded. JVM class loaders looks for the classes specified in the following order- Bootstrap classes :loads java libraries (rt.jar etc.) Extensions classes : loads external libraries in lib/ext paths. For example, <JAVA_HOME>/lib/ext etc. Classes in classpath: loads classes in CLASSPATH environment variable or system property java.class.path. (By default, the java.class.path property's value is ‘.’) Secure: Security is in-built into Java's language rules. It has no syntax for pointers. So it is impossible to access illegal memory. Java has extensive syntax (like private, protected) to secure data from being accessed by illegal objects. It also has comprehensive API with support for a wide range of cryptographic services and for Authentication and Access Control, Secure communication. Java Compiler flags error on illegal conversions and also makes sure that all java's language rules are adhered to

23 Portable and platform independent
Java Code can be compiled anywhere Bytecode can be executed anywhere Can you make any guesses which statement above is for portable and which one for platform independence?

24 Portable When java code executes, its behavior is exactly same in any java-aware system. There are no platform-specific code in java programs that causes compilation problems in any other OS. This makes Java programs are portable. There are no platform-specific code in java programs that causes compilation problems in any other OS. (For example in C if you include conio.h library, this will work only in Window OS and will not work in linux). Also some features that were considered not portable in C/C++ (like sizes of int, right shift operator behavior etc.) were eliminated for Java

25 Platform Independent A Java program requires JVM (part of JRE) to execute Java code. When java application starts to executes, Java Virtual Machine also starts. Bytecode has instructions that Java Virtual Machine can understand and execute. JVM converts the Bytecode to machine specific code. Java Bytecode can be copied on to any machine that has JVM and executed. This is what makes Java Platform Independent. “Write Once, Run any where” Is JVM platform independent?

26 JVM: perspectives JVM can be looked as
a runtime instance: JVM life cycle begins when applications starts to run ( that is when main method is called) and ends when the application ends. the abstract specification: Specification that Java team at Sun (Oracle) provides which tells JVM makers how they must design JVM for their OS. a concrete implementation: JVM that is built specifically targeted for an OS based on abstract specification . When we talk about JVM in these sessions, we mean a runtime instance of JVM

27 Interpreter vs JIT Java Bytecodes were originally designed to be interpreted by JVM meaning bytecode are translated to machine code without it being stored anywhere. Since bytecode verifier (which is part of JVM) performs runtime checks, line by line execution was important. Since speed became an issue, Just-in-Time Compilation (JIT) came into being. JIT converts chunks of code, stores it temporarily in memory and then executes the converted code. JIT compilers are typically bundled with or are a part of a virtual machine and do the conversion to native code at runtime, on demand. The compiler also does automatic register allocation and some optimization when it produces the bytecodes. Therefore, JIT is hybrid compiler.

28 Error handling in java Compilation error : generated by the compiler. Examples of situation when it arises: incorrect syntax, bracket mismatch, if keywords are used as variables Using uninitialized variables Unreachable code: while(false){…} Strong type checking Run-time error : generated by the JVM. Examples of situation when it arises: Attempt to divide an integral value by 0 or access array index beyond the defined range. Trying to access a class that does not exist at runtime. (What happens if you delete Hello.class and then run Hello. Java has a strong exception handing mechanism that allows programmers to handle such errors and come out of the situation gracefully.

29 Automatic garbage collection
The garbage collector is a tool that attempts to free unreferenced memory (memory occupied by objects that are no longer in use by the program) in programs. Automatic garbage collection is an integral part of Java and its run-time system. Java technology has no pointers. So there is no question of allocation and freeing by programmers. Does that mean Java does not support dynamic memory allocation? No. It means that Java takes care of memory and relieves the programmers from memory-related hassles. java –verbose:gc can be used to get more information about garbage collection process.

30 Classpath Classpath is an environment variable that java compiler and JVM (system class loader) use to locate the classes in the file system. To set the classpath temporarily in command line SET CLASSPATH=directory;%CLASSPATH%;. Command to set classpath while compiling javac –classpath dir1;dir2 Someclass.java Example: javac –classpath C:/MyJava Command to specify un-compiled source file to be compiled and included in the classpath javac – sourcepath dir1;dir2 Someclass Example: javac –sourcepath C:/MyJava Providing classpath while executing java –classpath directory1;directory2

31 Exercise to understand classpath
public class A{ public static void main(String[] args) { String curDir = System.getProperty("user.dir"); System.out.println(curDir); } This code is in C:\MyJava folder. If this code is executed from C:\MyJava, it prints the current directory. What command will make sure that this code can be executed from any location? (10 mins)

32 Commenting source code
Question: Why should you comment your code? How much should you comment? 3 types of comment Single line comment : // // this is a single line comment Multi-line comment: /* */ /* this is multi line comment */ Documentation Comment (Doc comment): /** */ /** This class is used to represent a stack. Murali 1.0, 08/16/2010 */

33 Some Guidelines for Doc comments
Who owns and edits the Doc Comments: usually the programmer Doc comments for classes, methods, fields: Brief description of what it does. In case longer description is required, link to an external document (word, pdf) can be included. For methods, whether they are thread-safe and what runtime exception they throw must be specified. Proper indentation of documentation for better readability. Entities for the less-than (<) and greater-than (>) symbols should be written < and >. Likewise, the ampersand (&) should be written &. Revisit this after threads and exception Visit this after finishing Java For More Information refer

34 javadoc Tool that is used to produce HTML pages by parsing through the documentation comment in java source code. Produces documentation for public and protected classes/members. Works on entire package or a single source file Usage on source file javadoc sourcefilename.java javadoc College.java

35 Nesting comments Valid Nesting /* // */ /** // */ ///* */ // /** */
/* // */ /** // */ ///* */ // /** */ Invalid Nesting /* */ and /** */ nested with itself and nested with each other gives error. /* /* */ */ /** /* */ */

36 Annotations Annotations are extra text starting symbol that are added in the Java program to provide information about a program. Annotations do not directly affect program semantics. They provide information about the program to tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.

37 Uses Annotations for the compiler Example:
@SuppressWarnings : can be used by the compiler to detect errors or suppress warnings Annotations for the application servers and tools Application server tools can process annotation information to generate code etc for services it provides like security etc. javadoc tool uses annotations like Runtime processing — Some annotations are available to be examined at runtime. This is how the documentation annotation is used. Try to generate javadoc for this with and without annotation and see the difference. /** * This class demonstrates documentation comments. XXX 1.2 */ public class A { * This method demonstrates prints Hello. args Unused. Nothing. public static void main(String args[]) { System.out.println("Hello"); }

38 Exercise Provide java doc comments for the class created in the previous exercise and generate HTML document files. Use documentation annotation. (10 mins)


Download ppt "Java: An introduction."

Similar presentations


Ads by Google