0% found this document useful (0 votes)
52 views

CSE 201 Java Lecture 1 TC

This document provides an introduction to the Java programming language. It describes Java as being simple, object-oriented, distributed, hybrid (compiled and interpreted), robust, secure, architecture-neutral, portable, high-performance, multithreaded and dynamic. It notes that Sun Microsystems developed Java in 1995 and discusses key Java concepts like object-orientation, distribution, compilation/interpretation, robustness and portability. It also provides an overview of typical Java development environments and the phases of editing, compiling, loading, verifying and executing a Java program.

Uploaded by

Palash Debnath
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

CSE 201 Java Lecture 1 TC

This document provides an introduction to the Java programming language. It describes Java as being simple, object-oriented, distributed, hybrid (compiled and interpreted), robust, secure, architecture-neutral, portable, high-performance, multithreaded and dynamic. It notes that Sun Microsystems developed Java in 1995 and discusses key Java concepts like object-orientation, distribution, compilation/interpretation, robustness and portability. It also provides an overview of typical Java development environments and the phases of editing, compiling, loading, verifying and executing a Java program.

Uploaded by

Palash Debnath
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

CSE 201: Object Oriented Programming Language

Java: Introduction

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 package structure
`

What is Java (Contd.)


`

Distributed
Fully supports IPv4 with structures to support IPv6 ` Includes support for Applets: small programs embedded in HTML documents
`

Compiled & Interpreted


Programs are compiled into Java Virtual Machine (JVM) code called bytecode. ` Each bytecode instruction is interpreted (translated into machine code) at the time of execution. (Penalty: speed)
`

What is Java (Contd.)


`

Robust
`Java is simple ` In-bound checking of array indices at runtime - no memory corruption or cryptic error messages ` Exception handling: try-catch-finally allows simplified error recovery ` Strongly typed language: many errors are detected during compilation time.

Portable
It supports the notion - write once, run anywhere. ` Java bytecodes can be executed on any platform containing a compatible JVM.
`

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.

History of Java In 1991, Sun Microsystems started a project targeting intelligent consumer electronic devices. ` The project ran into some difficulties, but the outcome from the project, the language Java, was widely accepted as a provider of dynamic content to Web pages. ` Now-a-days, Java has touched almost every spheres of the software industry.
`

Editions of Java
`

Java has three editions. ` Java 2 Platform, Standard Edition (J2SE) ` Used for developing Desktop-based application and networking applications. ` Java 2 Platform, Enterprise Edition (J2EE) ` Used for developing large-scale, distributed networking applications and Web-based applications. ` Java 2 Platform, Micro Edition (J2ME) ` Used for developing applications for small memory-constrained devices, such as cell phones, pagers and PDAs. We will work with Suns Java 2 Platform, Standard Edition (J2SE). ` Sun provides an implementation of this platform, called the J2SE Development Kit (JDK). ` We will use JDK version 6.0.

Java Class Libraries ` Java programs consist of pieces called classes. Classes include member variables and member functions (called methods)
` `

There exists a rich collection of existing classes in the Java class libraries, also known as the Java APIs (Application Programming Interfaces)

Java Class Libraries (Contd.) ` There are two aspects of learning the Java world.
`

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 the wheel.


`

Typical Java Development Environment

Java programs normally go through five phases.


`

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
`

Phase 1: Creating a Program


Any text editor or Java IDE (Integrated Development Environment) can be used to develop Java programs. ` Java source-code file names must end with the .java extension. ` Some popular Java IDEs are
`

NetBeans ` jEdit ` Eclipse ` Jbuilder ` JCreator ` Kawa etc.


`

Phase 2: Compiling a Java Program


`javac
`

Welcome.java

Compiles the source file Welcome.java (and other files if necessary), transforms the Java source code into bytecodes and places the bytecodes in a file named Welcome.class.
It searches the file Welcome.java in the current directory.
`

Bytecodes
They are not machine language binary code. ` They are independent of any particular microprocessor or hardware platform. ` They are platform-independent instructions. ` Another entity or interpreter is required to convert the bytecodes into machine codes that the underlying microprocessor understands. ` This is the job of the JVM (Java Virtual Machine)
`

JVM (Java Virtual Machine)


It is a part of the JDK and the foundation of the Java platform.
`
` `

It can be installed separately or with JDK. A virtual machine (VM) is a software application that simulates a computer, but hides the underlying operating system and hardware from the programs that interact with the VM. One of the main contributors for the slowness of Java programs compared to compiled machine language programs (i.e. C, C++, Pascal etc.).

JVM (Contd.)
It is the JVM that makes Java a portable language. ` The same bytecodes can be executed on any platform containing a compatible JVM. ` JVM is available for Windows, Unix, Linux and Solaris. ` The JVM is invoked by the java command. ` java Welcome ` It searches the class Welcome in the current directory and in the directories listed in the CLASSPATH environment variable and executes the main method of class Welcome. ` It issues an error if it cannot find the class Welcome or if class Welcome does not contain a method called main with proper signature (more on this will be discussed later)
`

Phase 3: Loading a Program into Memory


One of the components of the JVM is the class loader ` The class loader takes the .class files containing the programs bytecodes and transfers them to primary memory (RAM) ` The class loader also loads any of the .class files provided by Java that our program uses. ` The .class files can be loaded from a disk on our system or over a network (another PC in our LAN, or the Internet)
`

Phase 4: Bytecode Verification


Another component of the JVM is the Bytecode Verifier ` Its job is to ensure that bytecodes are valid and do not violate Javas security restrictions ` This feature helps to prevent Java programs arriving over the network from damaging our system ` Another contributor for making Java programs slow
`

Phase 5: Execution
Bytecodes are converted to machine language suitable for the underlying OS and hardware ` Recent JVM performs just-in-time (JIT) compilation to make program execution faster ` Java programs actually go through two compilation phases `

Source code -> Bytecodes ` Bytecodes -> Machine language


`

Why does Java not follow the following strategy?


Source Code -> JVM -> machine language

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

Examining JavaTest.java
Every program in Java consists of at least one class declaration defined by the programmer
`

A Java source file can contain multiple classes, but only one class can be a public class
`

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

A public class is accessible across packages

The source file name must match the name of the public class defined in the file with the .java extension.

Examining JavaTest.java (Contd.)


We can also place our classes into packages, but it is optional
`

When we do not specify any package for our class, the class is placed in a default unnamed package (more on packages will be discussed later)
` `

By convention, all class names in Java begin with a capital letter and capitalize the first letter of each word they include (e.g. SampleClassName)

Java is case sensitive. In fact Java file names are also case sensitive
`

Both javac and java work with case sensitive file names

Examining JavaTest.java (Contd.)


In Java, there is no provision to declare a class, and then define the member functions outside the class
` `

Body of every member function of a class (called method in Java) must be written when the method is declared

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


`

Java methods can be written in any order in the source file


`

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

Examining JavaTest.java (Contd.)


`
`

public static void main(String args[ ])


`

the starting point of every Java application.


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 the ClassName.methodName notation (more on static members will be discussed later) void means main does not return anything String args[ ] represents a function parameter that is an array of String objects (more on String will be discussed later). This array holds the command line arguments passed to the application

Here,
`
`

` `

Examining JavaTest.java (Contd.)


Think of JVM as a Java entity who tries to access the main method of class JavaTest. ` To do that main must be accessible from outside of class JavaTest. ` So, main must be declared as a public member of class JavaTest. ` Also, JVM wants to access main without creating an object of class JavaTest. ` So, main must be declared as static. ` Also JVM wants to pass an array of String objects containing the command line arguments. ` So, main must take an array of String as parameter.
`

Examining JavaTest.java (Contd.)


System.out.println() is used to print a line of text followed 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 (the actual class name is not important now) ` out represents the standard output (similar to stdout or cout) ` println is a public method of the class of which out is an object
`

Examining JavaTest.java (Contd.)


System.out.print() is similar to System.out.println(), but does not print a new line automatically ` System.out.printf() is used to print formatted output like printf() in C ` In Java, characters enclosed by double quotes () represents a String object, where String is a class of the Java API ` We can use the plus operator (+) to concatenate multiple String objects and create a new String object
`

Compiling a Java Program (JavaTest.java) ` If the source file contains multiple classes then javac will 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 .class extension .class files contain the bytecodes of each class

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

Executing a Java Program (JavaTest.class) ` Open a Command Prompt window and go to the bin directory (or use the same window used in the compilation step). ` Execute the following command `

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

Here java (the JVM) will look for the class file JavaTest.class and search for a public static void main(String args[ ]) method inside the class. ` If the JVM finds the above two, it will execute the body of the main method.
`

Executing a Java Program (Contd.)


If the JVM fails to locate the class , it will generate an error and will exit immediately.
`

Exception in thread "main" java.lang.NoClassDefFoundError: JavaTest Caused by: java.lang.ClassNotFoundException: JavaTest at 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

Examining Another Program: JavaTest2.java


class A{
private int a; public A( ){
this.a=0;

public class JavaTest2{


public static void main(String args[ ]){ A obj; obj = new A( ); obj.setA(10); System.out.println(obj.getA()); }

} public void setA(int a){


this.a = a;

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

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. We have 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 (&), arrow Operator (->) or indirection operator (*) ` Every java object has to be instantiated using the keyword new
`

Examining JavaTest2.java (Contd.) ` Two classes - A & JavaTest2 but only one public class JavaTest2 ` javac JavaTest2.java creates two class files ` A.class ` JavaTest2.class ` java JavaTest2 executes the program since class JavaTest2 contains the main method

Lecture Content
`

Java: How to Program


`

Chapter 1 & 2

You might also like