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



Similar documents
Java Interview Questions and Answers

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

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

Crash Course in Java

Moving from CS 61A Scheme to CS 61B Java

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

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

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

C++ INTERVIEW QUESTIONS

Java CPD (I) Frans Coenen Department of Computer Science

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

The Interface Concept

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

Example of a Java program

Introduction to Java

Lecture 5: Java Fundamentals III

Contents. 9-1 Copyright (c) N. Afshartous

CS506 Web Design and Development Solved Online Quiz No. 01

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

Object Oriented Software Design

AP Computer Science Java Subset

Fundamentals of Java Programming

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

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Install Java Development Kit (JDK) 1.8

History OOP languages Year Language 1967 Simula Smalltalk

El Dorado Union High School District Educational Services

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

Java from a C perspective. Plan

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Java Programming Fundamentals

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

Semantic Analysis: Types and Type Checking

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

The C Programming Language course syllabus associate level

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Java Basics: Data Types, Variables, and Loops

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

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Introduction to Object-Oriented Programming

More on Objects and Classes

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

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

CMSC 202H. ArrayList, Multidimensional Arrays

Basic Object-Oriented Programming in Java

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

Database Programming with PL/SQL: Learning Objectives

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

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

Chapter 1 Java Program Design and Development

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

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

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

Unit 6. Loop statements

13 Classes & Objects with Constructors/Destructors

Getting Started with the Internet Communications Engine

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

Introduction to Java. CS 3: Computer Programming in Java

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

An Overview of Java. overview-1

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

CS193j, Stanford Handout #10 OOP 3

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Chapter 5 Names, Bindings, Type Checking, and Scopes

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

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

In this Chapter you ll learn:

java Features Version April 19, 2013 by Thorsten Kracht

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Java Crash Course Part I

Chapter 2 Introduction to Java programming

Pemrograman Dasar. Basic Elements Of Java

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Sample CSE8A midterm Multiple Choice (circle one)

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

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

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

Chapter 13 - Inheritance

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

C++FA 5.1 PRACTICE MID-TERM EXAM

Glossary of Object Oriented Terms

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

15-214: Principles of Software Construction 8 th March 2012

Practical Session 4 Java Collections

Introduction to Programming

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

B.Sc (Honours) - Software Development

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

WRITING DATA TO A BINARY FILE

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Creating a Simple, Multithreaded Chat System with Java

Programming Languages CIS 443

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Transcription:

Introduction to Java Short Introduction to the Concepts of Programming in Java Overview over the most important constructs OOIS 1998/99 Ulrike Steffens Software Systems Institute ul.steffens@tu- harburg.de http:// www.sts.tu- harburg.de Data Types Two different kinds of data types primitive types reference types Primitive Types boolean char byte short int long float double OOIS-11-98-StWe-Java 2 1

Reference Types Predefined or user-defined Classes String Array The values of reference types are not manipulated directly. Instead handles (references) to the actual values are used. OOIS-11-98-StWe-Java 3 Reference Type Variables A variable of a reference type contains a reference to an anonymous object in storage. a Point a,b; An uninitialized variable contains a null-reference. Objects are anonymous. They have an immutable identity. Objects are created at run-time. new Point(0,0) b 0 0 OOIS-11-98-StWe-Java 4 2

Binding Reference Type Variables Assigning an object to a reference type variable, the variable gets a reference to the object as new value. The value of the object does not change a = new Point(0,0); b = new Point(3,4); Assigning values of other b variables means assigning the references! a = b May be a pitfall, as the object may change OOIS-11-98-StWe-Java 5 a a b 0 0 3 4 0 0 3 4 Comparing Objects Comparing two reference type variables means comparing the references they contain and, thus, comparing the identity of the referenced objects. a b 3 4 a == b c 3 4 a!= c OOIS-11-98-StWe-Java 6 3

Comparing the Contents of Objects The contents of objects belonging to pre-defined classes can be compared using the method equals. If you define a class of your own, equals by default only compares references, as == does. => You have to override equals for new defined classes. OOIS-11-98-StWe-Java 7 Creating New Data Types: class Class keyword defines new data type class ATypeName { /* class body goes here */ ATypeName a = new ATypeName(); Fields class DataOnly { int i; float f; boolean b; Each instance of DataOnly gets its own copy of the fields In a class, primitives get default values. OOIS-11-98-StWe-Java 8 4

Methods, Arguments and Return Values Methods: how you get things done in an object Traditionally called functions Can only be defined inside classes returntype methodname (/*argument list*/){ /* method body */ Example method call: int x = a.f(); //For object a OOIS-11-98-StWe-Java 9 The Argument List Types of the objects to pass in to the method Name (identifier) to use for each one Whenever you seem to be passing objects in Java, you re actually passing handles int size(string s){ return s.length(); OOIS-11-98-StWe-Java 10 5

Control Flow Statements if (condition) {... else {... (condition)? value1: value2 while (condition) {... do {... while (condition) for(int i = 0; i < 10; i++) {... switch(value){ case (value1):... ; case (value2):... ;... default:...; OOIS-11-98-StWe-Java 11 The static Keyword Normally each object gets its own data What if you want only one piece of data shared between all objects of a class? ( class data ) class StaticTest { static int i = 47; What if you want a method that can be called for the class, without an object? ( class method ) class StaticFun { static void incr() { StaticTest.i++; StaticFun.incr(); OOIS-11-98-StWe-Java 12 6

Guaranteed Initialization with the Constructor class Rock { Rock() { // This is the constructor System.out.println("Creating Rock"); public class SimpleConstructor { public static void main(string args[]) { for(int i = 0; i < 10; i++) new Rock(); OOIS-11-98-StWe-Java 13 Nuance We can deduce meaning from context Wash the shirt Wash the car Wash the dog Not shirtwash the shirt carwash the car dogwash the dog OOIS-11-98-StWe-Java 14 7

Method Overloading void wash(shirt s) { //... void wash(car c) { //... void wash(dog d) { //... Unique argument combinations distinguish overloaded methods OOIS-11-98-StWe-Java 15 Method Overloading One word, many meanings: overloaded class Tree { int height; Tree() { System.out.println("A seedling"); height = 0; Tree(int i) { System.out.println("A new Tree, " + i + " feet tall"); height = i; OOIS-11-98-StWe-Java 16 8

void info() { System.out.println("Tree is " + height + " feet tall"); void info(string s) { System.out.println(s + ": Tree is + height + " feet tall"); OOIS-11-98-StWe-Java 17 Default Constructor: Takes no Arguments Compiler creates one for you if you write no constructors class Bird { int i; public class DefaultConstructor { public static void main(string args[]) { Bird nc = new Bird(); // default! OOIS-11-98-StWe-Java 18 9

this: Handle to Current Object public class Leaf { private int i = 0; Leaf increment() { i++; return this; void print() { System.out.println("i = " + i); public static void main(string args[]) { Leaf x = new Leaf(); x.increment().increment().increment().print(); OOIS-11-98-StWe-Java 19 this in Constructors A very common kind to use this is in constructors to initialize data fields with the constructor's arguments public class Animal { private int numberoflegs; Animal(int numberoflegs) { this.numberoflegs = numberoflegs; OOIS-11-98-StWe-Java 20 10

Overloading on Return Values Why not also use return values in method overloading? void f() { //... int f() { //... Then what would this mean? f(); OOIS-11-98-StWe-Java 21 Member Initialization void f() { int i; // No initialization i++; Produces compile-time error Inside class, primitives are given default values if you don t specify values class Data { int i = 999; long l; // defaults to zero //... OOIS-11-98-StWe-Java 22 11

Array Initialization int a1[]; // this... int[] a1; // is the same as this! Creates a handle, not the array. Can t size it. To create an array of primitives: int a1[] = { 1, 2, 3, 4, 5 ; An array of class objects: Animal a[] = new Animal[20]; // 20 x null System.out.println(a.length + " animals"); for(int i = 0; i < a.length; i++) { a[i] = new Animal((i % 2 + 1) * 2); Bounds checked, length produces size OOIS-11-98-StWe-Java 23 Array Initialization Can also use bracketed list (The size is then fixed at compile-time) Integer[] a = { new Integer(1), new Integer(2), new Integer(3), ; If you do anything wrong either the compiler will catch it or an exception will be thrown OOIS-11-98-StWe-Java 24 12

Multi-dimensional Arrays It is possible to define multi-dimensional arrays in the same way as described. int[][] a; The brackets even may be distributed between type and identifier. int[] a[]; Initialization can be done directly int[][] a = { { 1, 2, 3, { 5, 6 ; It can also be done by nested iterations over the array and its components. arrays may not be rectangular OOIS-11-98-StWe-Java 25 Strings Strings are immutable objects of the class String. String literals are zero, one or more characters included within double quotes. When a binding to a string literal is executed for the first time, a new String object is created. If any other bindings to this literal appear, the respective variables will hold reference to the same object. String a = "abc"; String b = "abc"; a b 1 2 1 "abc" OOIS-11-98-StWe-Java 26 13

String Constructors String objects can also be created by calling a constructor. String constructors create new objects whenever they are called. String c = new String(" abc"); a b c "abc" "abc" There are several constructors defined for strings. OOIS-11-98-StWe-Java 27 String Concatenation Strings can be concatenated by using +. String c = "A " + "concatenation"; The concatenation also creates a new String object. Values of other types can be concatenated to strings, too. They are implicitly converted to String. String n = "Number " + 49; OOIS-11-98-StWe-Java 28 14

Package: the Library Unit import java.util.*; import java.util.vector; Managing name spaces Class members are already hidden inside class Class names could clash Need completely unique name Compilation units (.java files) Name of.java file == name of single public class Other non-public classes are not visible Each class in file gets its own.class file Program is a bunch of.class files (no.obj or.lib) OOIS-11-98-StWe-Java 29 Creating a Library of Classes package mypackage; public class is under the umbrella mypackage Client programmer must import mypackage.*; Creating unique package names Location on disk encoded into package name Convention: first part of package name is Internet domain name of class creator (reversed) Java interpreter uses CLASSPATH environment variable as starting point for search OOIS-11-98-StWe-Java 30 15

Library Location C:\DOC\Java\SomeDirectory\util CLASSPATH takes care of first part: CLASSPATH=.;D:\JAVA\LIB;C:\DOC\ JavaT Programs can be in any directory import SomeDirectory.util.*; public class LibTest { public static void main(string args[]) { Vector v = new Vector(); List l = new List(); Compiler starts search at CLASSPATH OOIS-11-98-StWe-Java 31 Java Access Control public Interface Access private Only Accessible Within the class protected Sort of private OOIS-11-98-StWe-Java 32 16

Friendly Default access, has no keyword public to other members of the same package, private to anyone outside the package. Easy interaction for related classes (that you place in the same package) Also referred to as package access OOIS-11-98-StWe-Java 33 public: Interface Access package c05.dessert; public class Cookie { public Cookie() { System.out.println("Cookie constructor "); void foo() { System.out.println("foo"); // Separate file: import c05.dessert.*; public class Dinner { public Dinner() { System.out.println("Dinner constructor"); public static void main(string args[]) { Cookie x = new Cookie(); //! x.foo(); // can't access OOIS-11-98-StWe-Java 34 17

private: Can t Touch That! class Sundae { private Sundae() { static Sundae makeasundae () { return new Sundae(); public class IceCream { public static void main(string args[]) { //! Sundae x = new Sundae(); Sundae x = Sundae.makeASundae(); OOIS-11-98-StWe-Java 35 protected Finer grained, deals with inheritance Generally: when you need it, you ll know OOIS-11-98-StWe-Java 36 18

An Object has an Interface Type name Interface Light on() off() brighten() dim() Object : Characteristics and Behavior Object Creation: Light lt = new Light(); Message: lt.on(); That s programming with objects! OOIS-11-98-StWe-Java 37 Inheritance Inheritance: Automatically duplicates the interface Shape draw() erase() Circle draw() erase() Square draw() erase() Line draw() erase() Reusing interface (and implementation) Objects related by inheritance all have the same type (interface) OOIS-11-98-StWe-Java 38 19

public class Shape { public void draw() { /* code drawing a shape */ public void erase() { /* code erasing a shape */ public class Circle extends Shape{ public void erase() { /* code erasing a circle */ OOIS-11-98-StWe-Java 39 Polymorphism One piece of code...... works with all this objects draw() erase() Shape Circle Square Line OOIS-11-98-StWe-Java 40 20

An Amazing Trick void dostuff(shape s) { s.erase();... s.draw(); Circle c = new Circle(); Triangle t = new Triangle(); Line l = new Line(); dostuff(c); // dynamic binding dostuff(t); dostuff(l); OOIS-11-98-StWe-Java 41 Composition vs. Inheritance Car Wheel[] Window[] Door[] Engine Pure composition: Code reuse Gray area Useful void f() void g() MoreUseful void f() void g() void u() void v() void w() Circle draw() erase() Inherit to extend or change interface Shape draw() erase() Sqare draw() erase() Line draw() erase() Pure inheritance: interface duplication for interchangeable objects OOIS-11-98-StWe-Java 42 21

An abstract Instrument Abstract classes leave some part of the implementation open Some methods and data may only be defined abstract class Instrument4 { int i; // storage allocated for each public abstract void play(); public String what() { return "Instrument4"; public abstract void adjust(); Rest of the code is the same Abstract classes cannot be instantiated by new OOIS-11-98-StWe-Java 43 An Instrument interface No concrete elements in interface You don t extend, you implement interface Instrument { void play(); // Automatically public String what(); void adjust(); class Guitar implements Instrument { public void play() { System. out.println("guitar.play()"); public String what() { return "Guitar"; public void adjust() { OOIS-11-98-StWe-Java 44 22

How to use Java on STS-Sun-Workstations? Set the paths PATH and CLASSPATH correctly by typing: def_jdk12 Create a file with your source code ending on.java Compile your code: javac filename.java Run your application java filename OOIS-11-98-StWe-Java 45 23