CSE 201 Java Lecture 1 Tc

Embed Size (px)

Citation preview

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    1/33

    CSE 201:

    Object Oriented Programming Language

    Java: Introduction

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    2/33

    What is Java

    ` A simple, object oriented, distributed, hybrid (compiled &

    interpreted), robust, secure, architecture-neutral,

    portable, high performance, multithreaded, and dynamic

    language.

    -- Sun Microsystems` Sun Microsystems developed Java in May 1995.` Object Oriented

    ` No free functions

    ` All codes belong to some class` Classes are in turn arranged in a hierarchy or packagestructure

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    3/33

    What is Java (Contd.)

    ` Distributed

    ` Fully supports IPv4 with structures to support IPv6

    ` Includes support for Applets: small programs embedded inHTML documents

    ` Compiled & Interpreted

    ` Programs are compiled into Java Virtual Machine (JVM) codecalled bytecode.

    `

    Each bytecode instruction is interpreted (translated intomachine code) at the time of execution. (Penalty: speed)

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    4/33

    What is Java (Contd.)

    ` Robust

    `Java is simple

    ` In-bound checking of array indices at runtime - no memorycorruption or cryptic error messages

    `Exception handling: try-catch-finally allows simplified errorrecovery` Strongly typed language: many errors are detected duringcompilation time.

    ` Portable

    ` It supports the notion - write once, run anywhere.

    ` Java bytecodes can be executed on any platform containing acompatible JVM.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    5/33

    Usage of Java

    ` Java can be used to develop a wide variety of applications

    ` Desktop-based applications

    ` Command-line programs

    `Window-based, interactive programs` Games etc.

    ` Internet-based applications` Client-Server applications

    ` Applications for small hand-held devices like mobile phones,PDAs, etc.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    6/33

    History of Java

    ` In 1991, Sun Microsystems started a projecttargeting intelligent consumer electronicdevices.

    ` The project ran into some difficulties, but theoutcome from the project, the language Java,was widely accepted as a provider of dynamiccontent to Web pages.

    ` Now-a-days, Java has touched almost everyspheres of the software industry.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    7/33

    Editions of Java

    ` Java has three editions.

    ` Java 2 Platform, Standard Edition (J2SE)

    ` Used for developing Desktop-based application and networkingapplications.

    ` Java 2 Platform, Enterprise Edition (J2EE)

    ` Used for developing large-scale, distributed networking applicationsand Web-based applications.

    ` Java 2 Platform, Micro Edition (J2ME)

    ` Used for developing applications for small memory-constraineddevices, such as cell phones, pagers and PDAs.

    ` We will work with SunsJava 2 Platform, Standard Edition (J2SE).` Sun provides an implementation of this platform, called theJ2SE

    Development Kit (JDK).

    ` We will use JDK version 6.0.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    8/33

    Java Class Libraries

    ` Java programs consist of pieces called classes.

    ` Classes include member variables andmember functions (called methods)

    ` There exists a rich collection of existingclasses in theJava class libraries, also knownas theJava APIs (Application ProgrammingInterfaces)

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    9/33

    Java Class Libraries (Contd.)

    ` There are two aspects of learning the Javaworld.` The Java language itself.

    ` The classes in the extensive Java class libraries.` Class libraries are developed/provided by` Compiler vendors,

    ` Independent software vendors (ISVs),` Us, the programmers

    `We should try to avoid reinventing thewheel.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    10/33

    Typical Java Development Environment` Java programs normally go through fivephases.

    ` Edit - create/edit the source code` Compile - compile the source code` Load - load the compiled code

    ` Verify - check against security restrictions` Execute - execute the compiled code

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    11/33

    Phase 1: Creating a Program` Any text editor or Java IDE (Integrated DevelopmentEnvironment) can be used to develop Java programs.

    ` Java source-code file names must end with the .javaextension.

    ` Some popular Java IDEs are` NetBeans

    ` jEdit

    ` Eclipse` Jbuilder` JCreator` Kawa etc.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    12/33

    Phase 2: Compiling a Java Programjavac Welcome.java`Compiles the source file Welcome.java(and other files if necessary),

    transforms the Java source code intobytecodes and places the bytecodes in afile named Welcome.class.

    `It searches the file Welcome.java inthe current directory.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    13/33

    Bytecodes

    ` They are not machine language binary code.` They are independent of any particularmicroprocessor or hardware platform.` They are platform-independent instructions.` Another entity or interpreter is required toconvert the bytecodes into machine codesthat the underlying microprocessorunderstands.` This is the job of theJVM (Java VirtualMachine)

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    14/33

    JVM (Java Virtual Machine)` It is a part of the JDK and the foundation of the Javaplatform.

    ` It can be installed separately or with JDK.

    ` A virtual machine (VM) is a software application thatsimulates a computer, but hides the underlying operatingsystem and hardware from the programs that interact withthe VM.

    ` One of the main contributors for the slowness of Javaprograms compared to compiled machine language programs(i.e. C, C++, Pascal etc.).

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    15/33

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    16/33

    Phase 3: Loading a Program intoMemory

    ` One of the components of the JVM is the classloader

    ` The class loader takes the .class files containing theprograms bytecodes and transfers them to primarymemory (RAM)

    ` The class loader also loads any of the .class filesprovided by Java that our program uses.

    ` The .class files can be loaded from a disk on oursystem or over a network (another PC in our LAN,or the Internet)

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    17/33

    Phase 4: Bytecode Verification

    ` Another component of the JVM is theBytecode Verifier

    ` Its job is to ensure that bytecodes are validand do not violate Javas security restrictions

    ` This feature helps to prevent Java programsarriving over the network from damaging oursystem

    `

    Another contributor for making Java

    programs slow

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    18/33

    Phase 5: Execution

    ` Bytecodes are converted to machine languagesuitable for the underlying OS and hardware

    ` Recent JVM performsjust-in-time (JIT)

    compilation to make program execution faster

    ` Java programs actually go through twocompilation phases -

    ` Source code -> Bytecodes

    ` Bytecodes -> Machine language` Why does Java not follow the following strategy?` Source Code -> JVM -> machine language

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    19/33

    Editing a Java Program (JavaTest.java)

    /*File Name: JavaTest.java

    */

    public class JavaTest{

    public static void main(String args[ ]){

    System.out.println(Hello Java);System.out.printf(I like %s\n, Java);String strDepartment = CSE;

    System.out.print(We study in +strDepartment+\n);} // end method main

    } // end class JavaTest - NOTE: no semicolon is required here

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    20/33

    Examining JavaTest.java

    ` Every program in Java consists of at least one classdeclaration defined by the programmer` A Java source file can contain multiple classes, butonly oneclass can be a public class

    ` Typically Java classes are grouped intopackages(similar to namespaces in C++)

    ` A public class is accessible across packages

    ` The source file name must match the name of thepublic class defined in the file with the .javaextension.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    21/33

    Examining JavaTest.java (Contd.)

    ` We can also place our classes into packages, but it isoptional` When we do not specify any package for our class, theclass is placed in a default unnamed package (more onpackages will be discussed later)

    ` By convention, all class names in Java begin with acapital letter and capitalize the first letter of each wordthey include (e.g. SampleClassName)

    ` Java is case sensitive. In fact Java file names are also casesensitive` Bothjavac andjava work with case sensitive file names

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    22/33

    Examining JavaTest.java (Contd.)

    ` In Java, there is no provision to declare a class, and thendefine the member functions outside the class` Body of every member function of a class (called

    method in Java) must be written when the method isdeclared

    ` So, there is no concept of declaring a prototype of amethod in Java

    ` Java methods can be written in any order in the sourcefile

    ` A method defined earlier in the source file can call amethod defined later in the source file

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    23/33

    Examining JavaTest.java (Contd.)

    `public static void main(String args[ ])` the starting point of every Java application.

    ` Here,

    ``

    ``

    public is used to make the method accessible by all

    static is used to make main a static method of class JavaTest. Static

    methods can be called without using any object; just using the class

    name is enough. Being static, main can be called by the JVM using theClassName.methodName notation (more on static members will bediscussed later)

    void means main does not return anything

    String args[ ] represents a function parameter that is an array ofString objects (more on String will be discussed later). This array holdsthe command line arguments passed to the application

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    24/33

    Examining JavaTest.java (Contd.)

    ` Think of JVM as a Java entity who tries to access themain method of class JavaTest.

    `To do that main must be accessible from outside ofclass JavaTest.

    `

    So, main must be declared as apublic member of class

    JavaTest.

    `Also, JVM wants to access main without creating anobject of class JavaTest.

    `So, main must be declared as static.

    ` Also JVM wants to pass an array of String objectscontaining the command line arguments.

    `So, main must take an array of String as parameter.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    25/33

    Examining JavaTest.java (Contd.)

    `System.out.println() is used to print a line of textfollowed by a new line

    `System is a class inside the Java API

    `out is a public static member of class System

    `out is an object of another class of the Java API (theactual class name is not important now)

    `out represents the standard output (similar to stdout orcout)

    `

    println is a public method of the class of which out is

    an object

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    26/33

    Examining JavaTest.java (Contd.)

    `System.out.print() is similar toSystem.out.println(), but does not print a new lineautomatically

    `System.out.printf() is used to print formattedoutput like printf() in C`In Java, characters enclosed by double quotes ()

    represents a String object, where String is a class ofthe Java API

    `

    We can use the plus operator (+) to concatenate

    multiple String objects and create a new Stringobject

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    27/33

    Compiling a Java Program (JavaTest.java)` If the source file contains multiple classes thenjavacwill produce separate .class files for each class

    ` Every compiled class in Java will have their own

    .class file having the name of the class with a .classextension` .class files contain the bytecodes of each class

    ` So, a .class file in Java contains the bytecodes of asingle class only

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    28/33

    Executing a Java Program (JavaTest.class)` Open a Command Prompt window and go to thebin directory (or use the same window used in thecompilation step).

    ` Execute the following command -

    ` java JavaTest` Note that we have omitted the .class extension here.

    ` Herejava (the JVM) will look for the class fileJavaTest.classand search for a public static voidmain(String args[ ]) method inside the class.` If the JVM finds the above two, it will execute thebody of the main method.

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    29/33

    Executing a Java Program (Contd.)

    ` If the JVM fails to locate the class , it will generate an error andwill exit immediately.Exception in thread "main" java.lang.NoClassDefFoundError: JavaTestCaused by: java.lang.ClassNotFoundException: JavaTestat java.net.URLClassLoader$1.run(Unknown Source)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(Unknown Source)at java.lang.ClassLoader.loadClass(Unknown Source)at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)at java.lang.ClassLoader.loadClass(Unknown Source)Could not find the main class: JavaTest. Program will exit.

    `If JVM fails to find the proper main method inside the class, it

    will generate an error and will exit immediately.

    ` Exception in thread "main" java.lang.NoSuchMethodError: main

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    30/33

    Examining Another Program: JavaTest2.java

    class A{private int a;public A( ){

    this.a=0;

    }

    public void setA(int a){

    this.a = a;

    }

    public int getA( ){return this.a;}

    }

    public class JavaTest2{public static void main(String args[ ]){

    A obj;

    obj = new A( );obj.setA(10);

    System.out.println(obj.getA());

    }

    }

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    31/33

    Examining JavaTest2.java (Contd.)

    ` The variable of a class type is called a reference` obj is a reference to an object of class A

    ` this is a reference to current object (not a pointer like C++)` Merely declaring a class reference is not enough. Wehave to use new to create an object` We access a public member of a class using the Dot (.)operator

    ` Dot (.) is the only member access operator in Java

    ` Java does not have BSRO (::), address operator (&), arrowOperator (->) or indirection operator (*)` Every java object has to be instantiated using thekeyword new

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    32/33

    Examining JavaTest2.java (Contd.)` Two classes - A & JavaTest2 but only onepublic class JavaTest2

    ` javac JavaTest2.java creates two class files` A.class` JavaTest2.class

    ` java JavaTest2 executes the program since classJavaTest2 contains the main method

  • 7/30/2019 CSE 201 Java Lecture 1 Tc

    33/33

    Lecture Content

    ` Java: How to Program` Chapter 1 & 2