Lecture 5 Java Introduction CPE 401 / 601 Computer Network Systems slides are modified from Ricky Sethi.

Slides:



Advertisements
Similar presentations
A Tutorial Introduction for C++ Programmers
Advertisements

Introduction To Java Objectives For Today â Introduction To Java â The Java Platform & The (JVM) Java Virtual Machine â Core Java (API) Application Programming.
Written by: Dr. JJ Shepherd
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Principles of Object-Oriented Software Development The language Java.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
Netprog 2002 Java Intro1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network.
Introduction to 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.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Developing User Interfaces (DUI) Chris North cs3724: HCI.
Java Software Solutions Lewis and Loftus Chapter 2 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Software Concepts -- Introduction.
Programming in Java; Instructor:Moorthy Introduction, Objects, Classes, Libraries1 Programming in Java Introduction.
OOP Languages: Java vs C++
Java Programming, 2E Introductory Concepts and Techniques Chapter 2 Creating a Java Application and Applet.
Programming Languages and Paradigms Object-Oriented Programming.
Java and C++, The Difference An introduction Unit - 00.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
1 Computer Systems -- Introduction  Chapter 1 focuses on:  the structure of a Java application  basic program elements  preparing and executing a program.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
OOP (Java): Simple/ OOP (Java) Objectives – –give some simple examples of Java applications and one applet 2. Simple Java Programs Semester.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
POS 406 Java Technology And Beginning Java Code
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Introduction to java Prepared By:-Pragnesh Patel Lect. In Computer Dept. NSIT,Jetalpur 1.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
C# Versus Java Author: Eaddy, Marc Source: Software Tools for the Professional Programmer. Dr. Dobb's Journal. Feb2001, Vol. 26 Issue 2, p74 Hong Lu CS699A.
1 Introduction to Java. 2 What is Java? A programming language. A platform –A virtual machine (JVM) definition. –Runtime environments in diverse hardware.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
National Taiwan University Department of Computer Science and Information Engineering National Taiwan University Department of Computer Science and Information.
Software Documentation Section 5.5 ALBING’s Section JIA’s Appendix B JIA’s.
We will talking about story of JAVA language. By Kristsada Songpartom.
CSE S. Tanimoto Java Introduction 1 Java A Programming Language for Web-based Computing with Graphics.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Creating a Java Application and Applet
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java Computer Industry Lab. 1 Programming Java Java Basics Incheon Paik.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 15: Java Basics Fundamentals of Web Programming.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Spring 2006 Special Topics in Computer Engineering: Java Intro 1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Copyright 2010 by Pearson Education APCS Building Java Programs Chapter 1 Lecture 1-1: Introduction; Basic Java Programs reading:
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
Information and Computer Sciences University of Hawaii, Manoa
Concurrent Object-Oriented Programming Java (VRH 7.7,8.6)
JAVA MULTIPLE CHOICE QUESTION.
Internet and Java Foundations, Programming and Practice
CompSci 230 Software Construction
Programming Language Concepts (CIS 635)
Java Programming Language
Object-Oriented Software Engineering
Introduction to Java Programming
(Computer fundamental Lab)
Chap 1. Getting Started Objectives
Chap 4. Programming Fundamentals
Presentation transcript:

Lecture 5 Java Introduction CPE 401 / 601 Computer Network Systems slides are modified from Ricky Sethi

So what the heck is Java (besides coffee, that is)?  A programming language.  Syntax and constructs are very similar to C++  A virtual platform  Java Virtual Machine is a software “machine” or “hypothetical chip”  Since it’s “virtual”, it can be implemented on any hardware  Cross-platform distribution achieved via.class binary file of bytecodes (instead of machine-dependent machine code)  Write Once, Run Anywhere  A class library  Standard APIs for GUI, data storage, processing, I/O, and networking. Java Introduction 2

Getting Java Brewing… 1.Download the latest Java SDK from  The SDK is a command-line based set of tools 2.A Text Editor 3.Web-browser that’s java-enabled (optional) 4.Some introductory links/guides/tutorials:  Java1/compile.html   Java Introduction 3

Mechanics of Writing Java Programs  Create a Java source file.  Must have the.java extension and contain only one public class.  Compile the source file into a bytecode file.  The Java compiler, javac, takes your source file and translates its text into instructions that the Java Virtual Machine (Java VM) can understand. The compiler puts these instructions into a.class bytecode file.  Run the program contained in the bytecode file.  The Java VM is implemented by a Java interpreter, java. This interpreter takes your bytecode file and carries out the instructions by translating them into instructions that your computer can understand. Java Introduction 4

Putting it all together public class Hello { public static void main(String args[]) { System.out.println( “ Hello, world! ” ); } 1.Put in: Hello.java 2.Compile with: javac Hello.java  Creates Hello.class 3.Run with: java Hello Java Introduction 5

Applications vs. Applets  A Java application:  Is a standalone program  Is interpreted by the Java Virtual Machine and run using the java command  Contains a main() method.  A Java applet:  Runs within a Java-enabled Web browser  extends the Applet or JApplet class (Inheritance)  Contains an init() or a paint() method (or both).  To create an applet, you'll perform the same basic steps: 1. Create a Java source file ( NameOfProgram.java ) and an HTML file ( NameOfHTMLFile.html ) 2. Compile the source file ( NameOfProgram.class ) 3. Run the program (either using java NameOfProgram or appletviewer NameOfHTMLFile.html ) Java Introduction 6

Java notes for C++ programmers  Everything’s an object  Every object inherits from java.lang.Object  No code outside of the class definition!  No global variables (use static variables instead)  Single inheritance only  Instead, implement interfaces  All classes are defined in.java files  One top level public class per file The file has to have the same name as the public class!  Syntax is similar (control structures are very similar).  Primitive data types are similar  But a bool is not an int  To print to stdout, use System.out.println() Java Introduction 7

Why Java?  Network Programming in Java is very different than in C/C++  much more language support Networking is at the core of the language  well defined error handling  no global variables  no struct, union types, goto’s, enums, bitfields, typedefs  no pointers! (garbage collection)  Threads are part of the language.  some support for common application level protocols (HTTP). Java Introduction 8

Requisite First Program (Application Version) Put in HelloWorld.java: public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); } Java Introduction 9

Compiling and Running HelloWorld.java javac HelloWorld.java java HelloWorld HelloWorld.class compile run bytecode source code Java Introduction 10

So what’s going on? The Java bytecode and interpreter at work!  Bytecode is an intermediate representation of the program (the class file)  Think of it as the machine-code for the Java Virtual Machine  The Java interpreter ( java ) starts up a new “Virtual Machine”  The VM starts executing the user’s class by running its main() method Java Introduction 11

Put in HelloWorld.java: import java.awt.Graphics; public class HelloWorld extends java.applet.Applet { public void paint(Graphics g) { g.drawString("Hello World“, 35, 15); } Put in test.html: Test the applet Test the applet Requisite First Program (Applet Version) Java Introduction 12

Java Language Basics  Data types same as in C++ (except bool )  bool,char,byte,short,int,long,float, double,string, etc.  Operators (same as C++)  Assignment: =, +=, -=, *=, …  Numeric: +, -, *, /, %, ++, --, …  Relational: ==. !=,, =, …  Boolean: &&, ||, !  Bitwise: &, |, ^, ~, >, …  Control Structures  more of what you expect: 1. conditional: if, if else, switch 2. loop: while, for, do 3. break and continue not an int! Java Introduction 13

Classes, References, & Packages  Classes and Objects  “All Java statements appear within methods, and all methods are defined within classes”.  Java classes are very similar to C++ classes (same concepts).  Instead of a “standard library”, Java provides a lot of Class implementations or packages  What are packages?  You can organize a bunch of classes and interfaces into a package (or library of classes) defines a namespace that contains all the classes.  Use the import keyword to include the packages you need import java.applet.*;  You need to use some java packages in your programs java.io (for Files, etc.), java.util (for Vectors, etc.)  References  No pointers  everything’s a reference!  classes, arrays Java Introduction 14

Exceptions  When a program carries out an illegal action, an exception is generated.  Terminology:  throw an exception: signal (in the method header) that some condition or error has occurred but we want to pass the buck and not deal with it.  catch an exception: deal with the error (or whatever) ourselves inside the function/method.  Catch it using a try/catch block (next slide).  In Java, exception handling is necessary  forced by the compiler  compilation errors!  Except for RunTimeExceptions Java Introduction 15

Try/Catch/Finally try { // code that can throw an exception } catch (ExceptionType1 e1) { // code to handle the exception } catch (ExceptionType2 e2) { // code to handle the exception } catch (Exception e) { // code to handle other exceptions } finally { // code to run after try or any catch } This block is always run Java Introduction 16

Exception Handling  Exceptions take care of handling errors  instead of returning an error, some method calls will throw an exception.  Can be dealt with at any point in the method invocation stack.  But if no method in the hierarchy handles it, results in an unchecked exception which generates a compiler error (unless it’s a RunTimeException)  Forces the programmer to be aware of what errors can occur and to deal with them. Java Introduction 17

Defining a Class  One top level public class per.java file.  Typically end up with many.java files for a single program with at least one containing a static public main() method (if they’re applications).  Class name must match the file name!  The compiler/interpreter use class names to figure out what the file name is.  Classes have these three features:  A constructor that’s used to allocate memory for the object, initiailize its elements, and return a reference to the object  Methods (function members)  Fields (data members) Java Introduction 18

A Sample Class public class Point { public Point(double x, double y) { this.x = x; this.y=y; } public double distanceFromOrigin(){ return Math.sqrt(x*x+y*y); } private double x,y; } Java Introduction 19

Objects and new  You can declare a variable that can hold an object: Point p;  But this doesn’t create the object! You have to use new : Point p = new Point(3.1,2.4);  new allocates memory and the garbage collector reclaims unused memory Java Introduction 20

Using Java objects  Just like C++:  object.method() or object.field  BUT, never like this (no pointers!)  object->method() or object->field  Event driven model:  Objects “register” to receive (and respond to) certain messages like button presses, mouse clicks, etc. (e.g., mouseUp(), mouseDown(), keyUp(), keyDown() ) Java Introduction 21

Strings are special  You can initialize Strings like this: String blah = "I am a literal ";  Or this ( + String operator): String foo = "I love " + “CET375";  Or this ( new operator): String foo = new String(“Yummy FooBars!”); Java Introduction 22

Arrays  Arrays are supported as a second kind of reference type (objects are the other reference type).  Although the way the language supports arrays is different than with C++, much of the syntax is compatible.  however, creating an array requires new  Index starts at 0.  Arrays can’t shrink or grow.  e.g., use Vector instead.  Each element is initialized.  Array bounds checking (no overflow!)  ArrayIndexOutOfBoundsException  Arrays have a.length  You can use array literals like C/C++ (no need for new keyword): Java Introduction 23

Array Examples Java Introduction 24 int x[] = new int[1000]; byte[] buff = new byte[256]; float[][] mvals = new float[10][10]; int[] values; int total=0; for (int i=0;i<value.length;i++) { total += values[i]; } String[] names = {“Joe”, “Sam”};

Java Introduction Reference Types  Objects and Arrays are reference types  Primitive types are stored as values  Reference type variables are stored as references (pointers that we can’t mess with) int x=3; int y=x; Point p = new Point(2.3,4.2); Point t = p; There are two copies of the value 3 in memory There is only one Point object in memory! 25

Passing arguments to methods  Primitive types: the method gets a copy of the value. Changes won’t show up in the caller  Pass by value  Reference types: the method gets a copy of the reference, the method accesses the same object  Pass by reference  There is no pass by pointers! Java Introduction 26

Comparing Reference Types  Comparison using == means:  “Are the references the same?” Do they refer to the same object?  Sometimes you just want to know if two objects/arrays are identical copies.  Use the.equals() method You need to write this for your own classes!  All objects and arrays are references! Java Introduction 27

Inheritance  Use the extends keyword to inherit from a super (or parent) class  No multiple inheritance  Use implements to implement multiple interfaces (abstract, virtual classes)  Use import instead of #include (not exactly the same but pretty close) to include packages (libraries) Java Introduction 28

Concurrent Multi-threaded Programming  Java is multithreaded!  Threads are easy to use.  Two ways to create new threads:  Extend java.lang.Thread Override “ run() ” method.  Implement Runnable interface Include a “ run() ” method in your class.  Usually, you’ll implement the Runnable interface  How to implement the Runnable interface:  Add a public void start() function: This is where you’ll initialize the thread and start() it  Add a public void stop() function: This is where you’ll set the boolean stopFlag to true  Add a public void run() function: This is where you’ll call repaint() to paint each new frame and handle any synchronized variables or methods 29

The synchronized Statement  Instead of mutex (a binary semaphore), use synchronized : synchronized ( object ) { // critical code here }  Also, declare a method as synchronized : synchronized int blah(String x) { // blah blah blah }  Can also use wait() and notify() to put threads on hold and wake them up again (e.g., to implement a pause or suspend feature)  Must be called within a synchronized block Java Introduction 30

Using Documentation Comments  Documentation comments are delimited by /** and */  javadoc automatically generates documentation  Copies the first sentence of each documentation comment to a summary table Write the first sentence with some care!  For each method/class, supply: followed by the parameter name and a short explanation followed by a description of the return value for author info, etc. Need to use “ javadoc –author ” for this… Java Introduction 31

javadoc  The Java Standard calls for every class, every method, every parameter, and every return value to have a comment  Write the method comments first!  If you can’t explain what a class or method does, you aren’t ready to implement it!  How to create HTML documentation:  Type: javadoc *.java in the directory containing your source code  This produces one HTML file for each class and an index.html file  Documenation is together with code! Must come immediately before the class, method, etc. Java Introduction 32