Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program



Similar documents
Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Object Oriented Software Design

AP Computer Science Java Subset

Object Oriented Software Design

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Java Interview Questions and Answers

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Java Application Developer Certificate Program Competencies

Crash Course in Java

Introduction to Java

Fundamentals of Java Programming

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java Programming Fundamentals

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Moving from CS 61A Scheme to CS 61B Java

An Overview of Java. overview-1

CS506 Web Design and Development Solved Online Quiz No. 01

DIPLOMADO DE JAVA - OCA

Java CPD (I) Frans Coenen Department of Computer Science

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Chapter 1 Java Program Design and Development

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

CS 111 Classes I 1. Software Organization View to this point:

Java SE 8 Programming

CMSC 202H. ArrayList, Multidimensional Arrays

CSC 551: Web Programming. Fall 2001

Lecture 5: Java Fundamentals III

Part I. Multiple Choice Questions (2 points each):

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

J a v a Quiz (Unit 3, Test 0 Practice)

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Java (12 Weeks) Introduction to Java Programming Language

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Java programming for C/C++ developers

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

To Java SE 8, and Beyond (Plan B)

Programmation 2. Introduction à la programmation Java

For Introduction to Java Programming, 5E By Y. Daniel Liang

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

More on Objects and Classes

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

CS 209 Programming in Java #1

Syllabus for CS 134 Java Programming

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

CS193j, Stanford Handout #10 OOP 3

Computer Programming I

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

Java Crash Course Part I

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chapter 1 Fundamentals of Java Programming

CS170 Lab 11 Abstract Data Types & Objects

C Compiler Targeting the Java Virtual Machine

CSC 551: Web Programming. Spring 2004

Quick Introduction to Java

Basic Programming and PC Skills: Basic Programming and PC Skills:

C++ INTERVIEW QUESTIONS

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Java the UML Way: Integrating Object-Oriented Design and Programming

Introduction to Java. CS 3: Computer Programming in Java

Facebook Twitter YouTube Google Plus Website

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

LAB4 Making Classes and Objects

Introduction to Java Lecture Notes. Ryan Dougherty

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Sources: On the Web: Slides will be available on:

CSE 452: Programming Languages. Acknowledgements. Contents. Java and its Evolution

INTRODUCTION TO JAVA PROGRAMMING LANGUAGE

The C Programming Language course syllabus associate level

Install Java Development Kit (JDK) 1.8

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

CS 106 Introduction to Computer Science I

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Glossary of Object Oriented Terms

Java with Eclipse: Setup & Getting Started

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Chapter 3. Input and output. 3.1 The System class

Introduction to Java Applets (Deitel chapter 3)

Java from a C perspective. Plan

1001ICT Introduction To Programming Lecture Notes

#820 Computer Programming 1A

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

Visual Basic Programming. An Introduction

Installing Java (Windows) and Writing your First Program

El Dorado Union High School District Educational Services

Contents. Java - An Introduction. Java Milestones. Java and its Evolution

Habanero Extreme Scale Software Research Project

The Java Virtual Machine and Mobile Devices. John Buford, Ph.D. Oct 2003 Presented to Gordon College CS 311

Transcription:

Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third edition is a free electronic book: http://www.mindview.net/books/tij/ Jill Seaman The fourth edition is much more up to date. 1 2 A simple java program Compilation Welcome.java //This program prints Welcome to Java! public class Welcome { public static void main(string[] args) { System.out.println("Welcome to Java!"); To compile the program enter at the prompt (Unix or Dos): javac Welcome.java javac is the java compiler If successful, this command creates the file Welcome.class in the same directory Welcome.class contains platform-independent bytecode bytecode is interpreted (executed) by a Java Virtual Machine (JVM), and will run on a JVM installed on any platform The program does NOT need to be recompiled to run on another platform. 3 4

Execution Java Platform To run the program enter at the prompt (Unix or Dos): workspace jill$ java Welcome Welcome to Java! workspace jill$ This runs the java bytecode on a Java Virtual Machine. a bundle of related programs that allow for developing and running programs written in the Java programming language two distributions: Java Runtime Environment (JRE) contains the part of the Java platform required to run Java programs (the JVM) Java Development Kit (JDK) is for developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method. The main method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. 5 6 Editions of Java Releases of Java Different editions of java target different application environments Java Card for smartcards. Different releases of Java JDK 1.0 (1996) Codename: Oak Java Platform, Micro Edition (Java ME) targeting environments with limited resources. Java Platform, Standard Edition (Java SE) targeting workstation environments. Java Platform, Enterprise Edition (Java EE) targeting large distributed enterprise or Internet environments. Each edition offers slightly different libraries (APIs) suited for the given environment. API: Application Programming Interface: the specification of the interface. JDK 1.1 (1997) J2SE 1.2 (1998) J2SE 1.3 (2000) J2SE 1.4 (2002) J2SE 5.0 (2004) (1.5) Java SE 6 (2006) (1.6) Java SE 7 (2011) (1.7) Java SE 8 (2014) (1.8) (I have this one) 7 8

Principles Features There were five primary goals in the creation of the Java language: It should be "simple, object-oriented and familiar" It should be "robust and secure" It should be "architecture-neutral and portable" It should execute with "high performance" It should be "interpreted, threaded, and dynamic" Interesting features of Java Object-oriented: everything is an object Inheritance Polymorphism: can use a subclass object in place of the superclass Garbage collection (dynamic memory allocation) Exception handling: built-in error handling Concurrency: built-in multi-threading Persistence: support for saving objects state between executions Platform independence: supports web programming 9 10 Characteristics of Pure object-oriented programming Everything is an object. attributes + operations A program is a bunch of objects telling each other what to do by sending messages a message as a request to call a method that belongs to a particular object Each object has its own memory made up of other objects. this is how to represent complex systems Every object has a type. its type is a class, the class specifies the methods of the object All objects of a particular type can receive the same messages. Even the instances of the subclasses 11 All objects in Java are really references Everything is treated as an object, using a single consistent syntax. However, the identifier you manipulate is actually a reference to an object String s; //this is just a ref, a pointer Safer to initialize a reference when you create it: String s = asdf ; Usually you use new to create new objects: String s = new String( asdf ); Note: references are on the run-time stack, objects are in heap. 12

Special case: primitive types These are NOT references, not objects They are stored on the run-time stack Size is not machine-dependent, always the same Wrapper: object that contains the primitive char c = 'x'; Character C = new Character(c); Classes in Java, fields A Class defines a type with fields (data) and methods (operations) Fields can be objects or primitives class ClassA { int i; Weeble w; Can create an object of this class using new: ClassA a = new ClassA(); Fields are accessible using dot operator a.i = 11; a.w = new Weeble(); 13 14 Default values for fields If you provide no explicit initialization to instance variables, they will be assigned the following default initial values Classes in Java, methods Methods in Java determine the messages an object can receive. They are functions that the object can execute on itself Syntax is very similar to C++ class ClassA { int i; Weeble w; int mult (int j) { return i*j; Methods are accessible using dot operator These apply to fields (and array elements), not to local variables. ClassA a = new ClassA(); a.i = 10; int x = a.mult(4); 15 16

Arrays in Java An array is ALWAYS initialized to default values (see slide 16) cannot access uninitialized elements by mistake Arrays have bounds checking unable to access memory outside its block (using the array): runtime error This is to enforce safety (though it requires overhead) Arrays are objects, contain primitives or references to objects member length returns size of array can access elements using [x] Weeble[] c = new Weeble[4]; for(int i = 0; i < c.length; i++) if(c[i] == null) // test for null reference c[i] = new Weeble(); 17 ArrayList class Must specify the element types (base type) when declaring: ArrayList<String> list = new ArrayList<String>(20); 20 is the initial capacity The base type must be a class (NOT primitive type). Basic methods: add(basetype x) Appends the specified element to the end of this list. Starts at position 0, increases capacity as necessary. get(int i) Returns the element at the specified position in this list. size() Returns the number of elements in this list (not the capacity). remove(int i) Removes the element at the specified position in this list, and closes the gap. 18 array vs. ArrayList array elements can be any type, ArrayList must contain objects. ArrayList can increase in size as needed (array size cannot be changed). ArrayList implements a partially filled array automatically. For an array, you must manage the size and implement add and remove operations yourself. ArrayList can be iterated over using a for-each loop: Accessing classes from libraries In Java libraries, elements are grouped into packages Packages have dotted path names (like internet domains) To use a class from a package, import the qualified class name: import java.util.arraylist; Or import the entire package: import java.util.*; ArrayList<String> list = new ArrayList<String>(20); //Some code here to fill the list for (String s : list) System.out.println(s); //does this for each String in list General syntax is: for (BaseType var : arraylist) stmt 19 20

Java library documentation Online documentation for Java 1.8 API http://docs.oracle.com/javase/8/docs/api/ java.lang is always implicitly loaded System class, contains out field (a static PrintStream) PrintStream has overloaded println methods Look for Date in the online documentation java.util.date shows constructor and other methods in documentation 21 static keyword When a field or method is declared static, it means that data or method is not tied to any particular object instance of that class Instances of the class share the same static fields Static methods may not access non-static fields class StaticFun { static i = 11; static void incr () { i++; Static fields and methods may be accessed without instantiating any objects by using the class name, or from an existing object. StaticFun.i = 100; StaticFun sf = new StaticFun(); sf.incr(); 22 A Java program Javadoc // HelloDate.java import java.util.*; public class HelloDate { public static void main(string[] args) { System.out.println("Hello, it's: "); System.out.println(new Date()); Standalone program: one class must have same name as file. that class must have a main method with signature as above. args are for command line arguments. public means method is available outside the file comments: /*... */ or //...to end of line 23 javadoc: a tool to extract comments embedded in source code and put them in a useful form: HTML files, viewable from a browser. Can regenerate the HTML files whenever the comments/code change. Uses a special comment syntax to mark the documentation inside the source code javadoc also pulls out the class name or method name that adjoins the comment(s). html files are similar to the online Java API documentation. Purpose is to document the public interface: the class names and public methods. 24

Javadoc syntax The javadoc commands occur only within /** */ comments Note the initial double asterisks. Each javadoc comment must precede the class definition, instance variable definition or method definition that it is documenting. /** A class comment */ public class DocTest { /** A variable comment */ public int i; /** A method comment */ public void f() { The javadoc comments may contain the following: embedded html code, especially for lists and formatting code snippets Javadoc tags This table summarizes the more commonly used tags. doc tags : special keywords that begin with @ that have special meaning to the javadoc tool. 25 26 /** * A Container is an object that contains other objects. * @author Trevor Miller * @version 1.2 * @since 0.3 */ public abstract class Container { /** * Create an empty container. */ protected Container() { /** * Return the number of elements contained in this container. * @return The number of objects contained */ public abstract int count(); /** * Accept the given visitor to visit all objects contained. * @param visitor The visitor to accept */ public abstract void accept(final Visitor visitor); /** * Determine whether this container is empty or not. * @return <CODE>true</CODE> if the container is empty: * <CODE>count == 0</CODE>, <CODE>false</CODE> otherwise */ public boolean isempty() { return (this.count() == 0); 27 Javadoc: generating the html files Use the javadoc command (from the JDK) to produce the html files: javadoc -d api Container.java The -d option indicates a target directory for the html files Generates multiple.html files click on api/container.html to see the result. For more details on javadoc, follow the javadoc links on the class website readings page: http://cs.txstate.edu/~js236/cs4354/readings.html 28

Operators in Java Assignment in Java Mathematical operators, same as C++ Assignment in Java is like in C++ + - * / % ++ -- += -= *= /= %= integer division truncates, like C++ For primitive types, values are copied int a; a = 10; Relational operators yield boolean result (not int) < > <= >= ==!= == over objects tests the value of the reference (the pointers) Logical operators &&! For objects, the reference is copied so both variables refer to the same object. Weeble b = new Weeble(); Weeble a; a = b; // a and b refer to same Weeble object changes to a will also affect b String + is concatenation: this yields a new String object: abc + def abcdef 29 Objects are passed by reference by default 30 Control flow in Java (same as C++) String if-else if(boolean-expression) else if(boolean-expression) The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. while, do-while, and for Methods (many more available): while(boolean-expression) do while(boolean-expression); for(initialization; Boolean-expression; step) length() Returns the length of this string. charat(int i) Returns the char value at the specified index (but this cannot appear on the left of an assignment, you cannot change the string). + for string concatenation break and continue (also with labels) switch like C++ String str = abc ; for (int i=0; i<str.length(); i++) System.out.println(str.charAt(i)); System.out.println(str+ def ); 31 32

tostring tostring is a method that is defined by default for every class public String tostring(); The String value returned should represent the data in the object. This makes it easy to output an object to the screen. The following are generally equivalent: System.out.println(w); System.out.println(w.toString()); You can override the default definition by redefining tostring for your class. class ClassA { private int i; private double x; public String tostring() { return ( i: +i+ x: +x); 33 Constructors Like C++: classes can have constructor functions to initialize their fields. these are named the same as the class, they have no return type, and can be overloaded. they are called automatically (primarily when new is used to create an instance of a class). if you don t create one for your class, a default (no-arg) constructor is created for you (initializes fields to default values). Unlike C++: you can call a constructor from within another constructor (see next slide) 34 this The this keyword which can be used only inside a method produces a reference to the object the method has been called on. in Java it s a reference, not a pointer class ClassA { int i; void seti(int i) { this.i = i; ClassA x = new ClassA(); x.seti(10); //inside seti, this is equal to x It can also be used to call a constructor from another constructor (Unlike C++): class ClassA { int i; ClassA(int i) { this.i = i; ClassA() { this(0); // calls ClassA(0) 35 Packages Classes can be grouped into packages: package mypackage; import... public class SmallBrain {... Declares these classes to belong to a package called mypackage package must come first in the file. Other classes (outside of mypackage) wanting access to SmallBrain must import mypackage, or fully specify it: mypackage.smallbrain. This is a mechanism to manage name spaces: this code will work with another package that has its own SmallBrain class. Anytime you create a package, you implicitly specify a directory structure: this file should be in a directory named mypackage 36

Packages: example To put your classes in a package called xx.mypackage: Declare the package on the first line of each java file package xx.mypackage; import... public class SmallBrain {... Put all the files in package xx.mypackage in the following directory:...src/xx/mypackage Make src the current directory: cd...src Access specifiers keywords that control access to the definitions they modify public: accessible to all other classes protected: accessible to classes derived from (subclasses of) the class containing this definition as well as other classes in the same package. package (unspecified, default): accessible only to other classes in the same package private: accessible only from within the class in which it is defined To compile: To run: javac xx/mypackage/*.java java xx.mypackage.classa Assuming ClassA contains a main method 37 38 The final keyword Java s final keyword has slightly different meanings depending on the context, but in general it says This cannot be changed. Data To create named constants (primitive type): public static final int VAL_THREE = 39; Use static so the class does not recreate it for each instance If you create an object that is final, it only means the reference cannot change, but the contents of the object itself could private final Value v2 = new Value(22); Cannot assign v2 to something else, but you could change its fields v2.setvalue(25); 39