Crash Course in Java



Similar documents
An Overview of Java. overview-1

Java Interview Questions and Answers

Java Crash Course Part I

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Java Programming Fundamentals

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

CS 106 Introduction to Computer Science I

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

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

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

Java from a C perspective. Plan

Tutorial: Getting Started

Fundamentals of Java Programming

Introduction to Java

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

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

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

Lecture 1 Introduction to Android

AP Computer Science Java Subset

public static void main(string[] args) { System.out.println("hello, world"); } }

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

Moving from CS 61A Scheme to CS 61B Java

CS506 Web Design and Development Solved Online Quiz No. 01

Getting Started with the Internet Communications Engine

The C Programming Language course syllabus associate level

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Chapter 1 Java Program Design and Development

CSC 551: Web Programming. Spring 2004

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

picojava TM : A Hardware Implementation of the Java Virtual Machine

Chapter 2 Introduction to Java programming

02 B The Java Virtual Machine

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

To Java SE 8, and Beyond (Plan B)

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

Habanero Extreme Scale Software Research Project

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

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

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

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

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

Object Oriented Software Design

java Features Version April 19, 2013 by Thorsten Kracht

Quick Introduction to Java

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

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

Programmation 2. Introduction à la programmation Java

Restraining Execution Environments

Object Oriented Software Design

Pemrograman Dasar. Basic Elements Of Java

JavaCard. Java Card - old vs new

INTRODUCTION TO JAVA PROGRAMMING LANGUAGE

Web Development in Java

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

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

CSC 551: Web Programming. Fall 2001

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

Introduction to Object-Oriented Programming

The Java Virtual Machine (JVM) Pat Morin COMP 3002

Java and Java Virtual Machine Security

Chapter 1 Fundamentals of Java Programming

2 Introduction to Java. Introduction to Programming 1 1

Creating a Simple, Multithreaded Chat System with Java

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

C# and Other Languages

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

Habanero Extreme Scale Software Research Project

JAVA IN A NUTSHELL O'REILLY. David Flanagan. Fifth Edition. Beijing Cambridge Farnham Köln Sebastopol Tokyo

Lecture 5: Java Fundamentals III

Chapter 7D The Java Virtual Machine

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

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

University of Twente. A simulation of the Java Virtual Machine using graph grammars

1. Overview of the Java Language

Java CPD (I) Frans Coenen Department of Computer Science

Introduction to Java. CS 3: Computer Programming in Java

Java SE 8 Programming

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

Java programming for C/C++ developers

Java applets. SwIG Jing He

Explain the relationship between a class and an object. Which is general and which is specific?

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

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

Chapter 6: Programming Languages

An Incomplete C++ Primer. University of Wyoming MA 5310

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming

Building a Multi-Threaded Web Server

Fachbereich Informatik und Elektrotechnik SunSPOT. Ubiquitous Computing. Ubiquitous Computing, Helmut Dispert

Installing Java (Windows) and Writing your First Program

General Introduction

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

ECE 122. Engineering Problem Solving with Java

1 The Java Virtual Machine

C++ INTERVIEW QUESTIONS

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

What Perl Programmers Should Know About Java

Transcription:

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 Computing Netprog 2002 Java Intro 1

What is Java? A programming language. As defined by Gosling, Joy, and Steele in the Java Language Specification A platform A virtual machine (JVM) definition. Runtime environments in diverse hardware. A class library Standard APIs for GUI, data storage, processing, I/O, and networking. Netprog 2002 Java Intro 2

Why Java? Network Programming in Java is very different than in C/C++ much more language support error handling no pointers! (garbage collection) threads are part of the language. some support for common application level protocols (HTTP). dynamic class loading and secure sandbox execution for remote code. source code and bytecode-level portability. Netprog 2002 Java Intro 3

Java notes for C++ programmers Everything is an object. Every object inherits from java.lang.object No code outside of class definition! No global variables. Single inheritance an additional kind of inheritance: interfaces All classes are defined in.java files one top level public class per file Netprog 2002 Java Intro 4

More for C++ folks Syntax is similar (control structures are very similar). Primitive data types similar bool is not an int. To print to stdout: System.out.println(); Netprog 2002 Java Intro 5

First Program public class HelloWorld { } public static void main(string args[]) { } System.out.println("Hello World"); Netprog 2002 Java Intro 6

Compiling and Running HelloWorld.java javac HelloWorld.java source code run compile java HelloWorld HelloWorld.class bytecode Netprog 2002 Java Intro 7

Java bytecode and interpreter bytecode is an intermediate representation of the program (class). The Java interpreter starts up a new Virtual Machine. The VM starts executing the users class by running it s main() method. Netprog 2002 Java Intro 8

PATH and CLASSPATH The java_home/bin directory is in your $PATH If you are using any classes outside the java or javax package, their locations are included in your $CLASSPATH Netprog 2002 Java Intro 9

The Language Data types Operators Control Structures Classes and Objects Packages Netprog 2002 Java Intro 10

Java Data Types Primitive Data Types: not an int! boolean true or false char unicode! (16 bits) byte signed 8 bit integer short signed 16 bit integer int signed 32 bit integer long signed 64 bit integer float,double IEEE 754 floating point Netprog 2002 Java Intro 11

Other Data Types Reference types (composite) classes arrays strings are supported by a built-in class named String string literals are supported by the language (as a special case). Netprog 2002 Java Intro 12

Type Conversions conversion between integer types and floating point types. this includes char No automatic conversion from or to the type boolean! You can force conversions with a cast same syntax as C/C++. int i = (int) 1.345; Netprog 2002 Java Intro 13

Operators Assignment: =, +=, -=, *=, Numeric: +, -, *, /, %, ++, --, Relational: ==.!=, <, >, <=, >=, Boolean: &&,,! Bitwise: &,, ^, ~, <<, >>, Just like C/C++! Netprog 2002 Java Intro 14

Control Structures More of what you expect: conditional: if, if else, switch loop: while, for, do break and continue (but a little different than with C/C++). Netprog 2002 Java Intro 15

Exceptions Terminology: throw an exception: signal that some condition (possibly an error) has occurred. catch an exception: deal with the error (or whatever). In Java, exception handling is necessary (forced by the compiler)! Netprog 2002 Java Intro 16

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 } Netprog 2002 Java Intro 17

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. Forces the programmer to be aware of what errors can occur and to deal with them. Netprog 2002 Java Intro 18

Concurrent Programming Java is multithreaded! threads are easy to use. Two ways to create new threads: Extend java.lang.thread Overwrite run() method. Implement Runnable interface Include a run() method in your class. Starting a thread new MyThread().start(); new Thread(runnable).start(); Netprog 2002 Java Intro 19

The synchronized Statement Java is multithreaded! threads are easy to use. Instead of mutex, use synchronized: synchronized ( object ) { } // critical code here Netprog 2002 Java Intro 20

synchronized as a modifier You can also declare a method as synchronized: synchronized int blah(string x) { } // blah blah blah Netprog 2002 Java Intro 21

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. Netprog 2002 Java Intro 22

Defining a Class One top level public class per.java file. typically end up with many.java files for a single program. One (at least) has a static public main() method. Class name must match the file name! compiler/interpreter use class names to figure out what file name is. Netprog 2002 Java Intro 23

Sample Class (from Java in a Nutshell) public class Point { public double x,y; public Point(double x, double y) { this.x = x; this.y=y; } public double distancefromorigin(){ return Math.sqrt(x*x+y*y); } } Netprog 2002 Java Intro 24

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); there are other ways to create objects Netprog 2002 Java Intro 25

Using objects Just like C++: object.method() object.field BUT, never like this (no pointers!) object->method() object->field Netprog 2002 Java Intro 26

Strings are special You can initialize Strings like this: String blah = "I am a literal "; Or this ( + String operator): String foo = "I love " + "RPI"; Netprog 2002 Java Intro 27

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 Netprog 2002 Java Intro 28

Array Examples int x[] = new int[1000]; byte[] buff = new byte[256]; float[][] mvals = new float[10][10]; Netprog 2002 Java Intro 29

Notes on Arrays 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 Netprog 2002 Java Intro 30

Array Example Code int[] values; int total=0; for (int i=0;i<value.length;i++) { } total += values[i]; Netprog 2002 Java Intro 31

Array Literals You can use array literals like C/C++: int[] foo = {1,2,3,4,5}; String[] names = { Joe, Sam }; Netprog 2002 Java Intro 32

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). There are significant differences! Netprog 2002 Java Intro 33

Primitive vs. Reference Types int x=3; int y=x; There are two copies of the value 3 in memory Point p = new Point(2.3,4.2); Point t = p; There is only one Point object in memory! Point p = new Point(2.3,4.2); Point t = new Point(2.3,4.2); Netprog 2002 Java Intro 34

Passing arguments to methods Primitive types: the method gets a copy of the value. Changes won t show up in the caller. Reference types: the method gets a copy of the reference, the method accesses the same object! Netprog 2002 Java Intro 35

Example int sum(int x, int y) { x=x+y; return x; } void increment(int[] a) { for (int i=0;i<a.length;i++) { a[i]++; } } Netprog 2002 Java Intro 36

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! Netprog 2002 Java Intro 37

Packages You can organize a bunch of classes and interfaces into a package. defines a namespace that contains all the classes. You need to use some java packages in your programs java.lang java.io, java.util Netprog 2002 Java Intro 38

Importing classes and packages Instead of #include, you use import You don t have to import anything, but then you need to know the complete name (not just the class, the package). if you import java.io.file you can use File objects. If not you need to use java.io.file objects. Netprog 2002 Java Intro 39

Sample Code Sum.java: reads command line args, converts to integer, sums them up and prints the result. Sum1.java: Same idea, this one creates a Sum1 object, the constructor then does the work (instead of main). Netprog 2002 Java Intro 40

More Samples Multiple Public classes: need a file for each class. Tell the compiler to compile the class with main(). automatically finds and compiles needed classes. Circle.java, CircleTest.java, Point.java, Threads.java, ExceptionTest.java Netprog 2002 Java Intro 41