Selected Java Topics

Similar documents
1 Shyam sir JAVA Notes

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

2 rd class Department of Programming. OOP with Java Programming

Compaq Interview Questions And Answers

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Introduction to Programming Using Java (98-388)

Assumptions. History

Today. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time

Special Topics: Programming Languages

15CS45 : OBJECT ORIENTED CONCEPTS

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Brief Summary of Java

Introduction to Java

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

CMSC 331 Second Midterm Exam

3. Java - Language Constructs I

Operators and Expressions

CSC Java Programming, Fall Java Data Types and Control Constructs

Programming. Syntax and Semantics

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Introduction to Java

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Index COPYRIGHTED MATERIAL

COT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Core JAVA Training Syllabus FEE: RS. 8000/-

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Class, Variable, Constructor, Object, Method Questions

Modern Programming Languages. Lecture Java Programming Language. An Introduction

CS 11 java track: lecture 3

CH. 2 OBJECT-ORIENTED PROGRAMMING

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

20 Most Important Java Programming Interview Questions. Powered by

CS260 Intro to Java & Android 03.Java Language Basics

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Declarations and Access Control SCJP tips

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

CSC 1214: Object-Oriented Programming

Object Oriented Java

National University. Faculty of Computer Since and Technology Object Oriented Programming

Rules and syntax for inheritance. The boring stuff

Pace University. Fundamental Concepts of CS121 1

Points To Remember for SCJP

Introduction to Java Written by John Bell for CS 342, Spring 2018

CMSC 132: Object-Oriented Programming II

C++ Programming: Polymorphism

CS 231 Data Structures and Algorithms, Fall 2016

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Java: introduction to object-oriented features

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CMSC 132: Object-Oriented Programming II

Fundamentals of Object Oriented Programming

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

CS2110 Fall 2011 Lecture 25. Under the Hood: The Java Virtual Machine, Part II

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT.

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Introduction to Object-Oriented Programming

CMSC 331 Second Midterm Exam

Computer Science II (20073) Week 1: Review and Inheritance

PESIT Bangalore South Campus

Lecture 4: Extending Classes. Concept

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Page 1

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Polymorphism. return a.doublevalue() + b.doublevalue();

Answer1. Features of Java

STRUCTURING OF PROGRAM

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Computer Components. Software{ User Programs. Operating System. Hardware

Self-test Java Programming

CS211 Spring 2005 Prelim 1 March 10, Solutions. Instructions

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

Java Object Oriented Design. CSC207 Fall 2014

Object Oriented Programming Exception Handling

Written by John Bell for CS 342, Spring 2018

Certified Core Java Developer VS-1036

Exercise: Singleton 1

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Chapter 6 Introduction to Defining Classes

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Example: Count of Points

Introduction to Programming (Java) 2/12

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Java Application Development

Example: Count of Points

CS Exam 1 Review Suggestions

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

CHAPTER 1. Introduction to JAVA Programming

Types, Values and Variables (Chapter 4, JLS)

Transcription:

Selected Java Topics Introduction Basic Types, Objects and Pointers Modifiers Abstract Classes and Interfaces Exceptions and Runtime Exceptions Static Variables and Static Methods Type Safe Constants Swings and AWT Type Casting Java Development Environments Advanced Java Features 1-1 Introduction Java was introduced in May 1995 by Sun MicroSystems. A pure object oriented programming language. Highly portable - same byte code on all supported platforms. Secure and Internet ready. Just-in-time (JIT) compiler makes it comparable to native language (like C/C++). Based on C++ but removed many dangerous features. Build-in exception handling. 1-2

Basic Types, Objects and Pointers Basic types are NOT objects: boolean - true or false char (16-bit Unicode) byte (8-bit signed, from -128 to 127) short (16-bit signed, from -32,768 to 32,767) int (32-bit signed, from -2,147,483,648 to 2,147,483,647) long (64-bit signed, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) float (32-bit, range roughly ±3.40282347 1038, 6-7 significant decimal digits) double (64-bit, range roughly ±1.79769313486231570 10308, 15 significant decimal digits) Anything other than these basic types is an object. All objects are created in the system s memory heap. 1-3 Objects and Pointers Objects cannot be moved out from the memory heap. When we need to use an object, we create, in the local memory, a pointer to the desired object, and use that pointer instead. As a result, when programming Java, we are dealing with pointers most of the time. (Surprise!) 1-4

Pointer Arithmetic Pointer arithmetic allows programmers a very high degree of flexibility in programming. However, it will also cause serious problems if used carelessly. Unlike C and C++, Java does NOT allow pointer arithmetic. Therefore, Java is much safer than C and C++. 1-5 Parameter Passing In Java, all the parameters passed into a method are passed by value, that means a copy of the variables is made into the method s local memory. If the method changes the values of the parameters, the calling method will NOT be able to see the changes. 1-6

Parameter Passing If an object is passed into a method. It is actually the pointer to the object being passed in and copied. The result is that if the method changes the content of object, the calling method will be able to see the change. However, if the method assigns another object to the pointer passed in, the calling method will NOT be able to see the new object. 1-7 Example public class Test public static void toupper (String s) s = s.touppercase (); System.out.println (s); java Test hello HELLO hello public static void main (String [] args) String s = hello ; System.out.println (s); toupper (s); System.out.println (s); 1-8

Arrays Java also allows programmers to use arrays to hold collections of information. Arrays are real Java objects. The size of an array cannot be changed. The length member will tell us how many elements are in the array. int size = array.length; Java arrays are safer than C/C++ arrays as the Java Virtual Machine will check for boundary before allowing access to the elements stored in the array. 1-9 Garbage Collection All objects are created in the system s memory heap and are managed by the system s garbage collecting mechanism. If an object is no longer needed, the memory allocated to this object will be reclaimed on the next Garbage Collection. The users (or the programmers) do not have control on when the Garbage Collection will be executed. 1-10

Modifiers private friendly protected public final abstract static 1-11 private private class - only useful if defined as inner class (more on inner class later). private method - only the class that defines the method can use it. private variable - only the class that defines the variable can use it. 1-12

friendly The default modifier. friendly class - can be extended and instantiated by everyone in the same package. friendly method - can be used by everyone in the same package. friendly variable - can be used by everyone in the same package. 1-13 protected protected class - only useful if defined as inner class. protected method - can only be used by the class itself and its subclass, as well as everyone in the same package. protected variable - can only be used by the class itself and its subclass, as well as everyone in the same package. 1-14

public public class - can be extended and instantiated by everyone. There can be at most one public class in each Java file. The name of the file must be the same as the public class, with.java append as extension. public method - can be used by everyone. public variable - can be read and written by everyone. 1-15 final final class - a class that cannot be extended. final method - a method that cannot be overridden. final variable - a variable of which the value cannot be changed - i.e. it is a constant - a value must be provided when the variable is declared. final int PI = 3.15149; 1-16

abstract abstract class - a class that is declared with the abstract keyword. abstract method - a method that is declared with the abstract keyword, there is no need to provide implementation for abstract method. If a class contains any abstract method, it has to be declared as an abstract class. abstract and final cannot be used at the same time - i.e. a class or method cannot be abstract and final at the same time. 1-17 static static variable - a variable that belongs to the class, not to the object (instance of the class) - if one object changes its value, the change will be effective to all objects of the same class. static method - a method that belongs to the class, not to the object - it does not need an instance to be used. 1-18

Inner Class A class that is defined inside another class. Inner class is a member of its defining class, so it can use all other members (variable, method) from that class directly without passing in a reference of the object. 1-19 Abstract Classes and Interfaces An abstract class cannot be instantiated. An interface is a class that has only abstract methods. By default, all the methods in an interface should be public. 1-20

Abstract Classes A class that extends an abstract class will not be abstract if and only if it provides implementation to all the abstract methods that are defined in the super classes. Use an abstract class if you have some common implementation that would be beneficial to all the subclasses. 1-21 Interfaces Interfaces can be used to define the operations required to implement a class - we will use this technique extensively in our course. Interfaces are also useful if we have to extend from more than one class - Java does not support multiple inherence - i.e. it does not allow you to extend from more than one class - however, it allows your class to implement more that one interface. 1-22

Example Shape Circle Rectang le Triang le Line 1-23 Shape Interface public interface Shape public void draw (Location l, Color c); public void erase (); public void move (Location newlocation); 1-24

Shape Abstract Class public abstract class Shape private Location savedlocation; private Color savedcolor; private Color backgroundcolor; public void abstract draw (Location l, Color c); public void erase () draw (savedlocation, backgroundcolor); public void move (Location newlocation) erase (); draw (newlocation, savedcolor); 1-25 Exceptions and Runtime Exceptions Throwable Exception Error RuntimeException 1-26

Exceptions An exception condition will occur if: an exception is thrown inside the method the method calls another method that throws an exception. The exception must be handled by either: caught by a try-catch block; or declared in the method signature Java compiler will enforce that every Exception is handled properly. 1-27 Runtime Exceptions RuntimeException is extended from Exception. RuntimeException does not have to be declared in the method signature. RuntimeException can be handled as a regular Exception. However, if you are confident that the RuntimeException will not occur under certain situation, you do not have to catch them or declare them in the method signature. 1-28

Static Variables and Static Methods Static variables and static methods belongs to the class, not the object. Static variables and static methods can be used without creating the object first. Useful in implementing the Singleton pattern and in giving each object of the class an unique ID. 1-29 The Singleton Pattern A design pattern provides a ready-made solution to design problems. The singleton pattern is a design pattern in that we only want to have a single instance of the class. A singleton class usually does not allow the user to create the object directly. Instead it provides a method to get the instance. We enforce this by making the constructor of the class private or protected. 1-30

Singleton Example public final class Singleton static Singleton theonlyinstance = null; // declare the constructor private so the // user cannot create the instance directly private Singleton () public static Singleton getinstance () if (theonlyinstance == null) theonlyinstance = new Singleton (); return theonlyinstance; 1-31 Unique ID Example public class Student static private int nextid = 1; private int id; public Student () id = nextid++; public int getid () return id; public String tostring () return ( Student + id); 1-32

Java Constants Java allows us to define constants: public interface Season public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3; public static final int WINTER = 4; public static int gettemperature (int season); 1-33 Java Constants We can use the constants directly: int springtemperature = Season.getTemperature (Season.SPRING); What happens if we pass in a zero or negative number: int currenttemperature = Season.getTemperature (0); int currenttemperature = Season.getTemperature (-1); int currenttemperature = Season.getTemperature (5); All these code will compile correctly, but the code will give us problem during runtime. 1-34

Type Safe Constants Java also allows us to define type safe constants: public final class SeasonConstants public static final SeasonConstants SPRING = new SeasonConstants ( spring ); public static final SeasonConstants SUMMER = new SeasonConstants ( summer ); public static final SeasonConstants FALL = new SeasonConstants ( fall ); public static final SeasonConstants WINTER = new final SeasonConstants ( winter ); 1-35 Type Safe Constants private String name; private SeasonConstants (String name) this.name = name; public String tostring () return name; 1-36

Usage This is how you can use type safe constants: public interface Season public static int gettemperature (SeasonConstants season); int springtemperature = Season.getTemperature (SeasonConstants.SPRING); 1-37 Oops What happens if we pass in a zero or negative number: int currenttemperature = Season.getTemperature (0); int currenttemperature = Season.getTemperature (-1); int currenttemperature = Season.getTemperature (5); Oops, the compiler will not allow us to do this. 1-38

Discussion Why the constructor is defined as a private constructor? What happens if the constructor is not private? Why the class SeasonConstants is defined as a final class? What happens if the class is not a final class? Why the constants is defined as static constants? Will this give us any benefits? 1-39 Swing and AWT Swing is an extension of AWT (Abstract Window Toolkit) Swing has several advantages over AWT: Uniform look-and-feel across different platforms The look-and-feel is configurable More powerful components Fix some bugs on the AWT 1-40

Swing Swing was introduced in Java 1.1, but is not part of the Java core distribution until Java 1.2 In Java 1.1, swing components are distributed in the package com.sun.java.swing In Java 1.2 swing components are distributed in the package javax.swing 1-41 Swing and Applet Currently both Netscape 4.7 and Internet Explore 5.0 do NOT support Swing. Appletviewer that comes with JDK is the only browser that support Swing. If you are writing an applet and your target users are the open public, avoid using Swing. 1-42

Type Casting Type Casting is used to change an object of one type into another type. ClassCastException will be thrown if converting into an incompatible type. ClassCastException is a RuntimeException and needs to be caught if you are not sure whether the conversion will be successful or not. Two types of casting: upcasting downcasting 1-43 Upcasting Converting an object into one of its super classes. Example: Object obj = new MyClass (); Upcasting is implicit, i.e. you don t have to explicitly write anything to perform an upcasting (although you can.) Upcasting is safe and always possible. 1-44

Downcasting Converting an object into one of its subclasses. Example: MyClass myinstance = (MyClass) obj; Downcasting is not always safe. It is possible that an object will be downcast into an incompatible object (and as a result a ClassCastException will be thrown.) Therefore, downcasting is not implicit and needs to be written out (see example above) and ClassCastException needed to be caught if necessary. 1-45 Java Development Environments JDK (Java Development Kit) From Sun MicroSystems (http://www.sun.com) Current Release 1.4.1 Command line interface only free JCreator From Xinox Software (http://www.jcreator.com) Current Release 2.5 IDE Need JDK free Lite edition 1-46

IDEs DOs and DON Ts Editing Syntax Highlighting Parenthesis Matching Compilation Compile within IDE Errors Locating Debugging Break Points Stepping through Code Code Generation Produce proprietary (nonstandard Java) code Produce unnecessary code Visual Editing Hard to position components precisely Produce non-standard Java Code 1-47 Advanced Java Features Here is a list of some advanced Java features that we will not cover: Thread Programming (Using and programming) Java Beans RMI (Remote Method Invocation) JNI (Java Native Interface) Java2D and Java3D (Advanced Java Graphic Toolkits) For more information about these features, consult any good Java reference available from book stores. Some of these references are listed in the course web page and are available for download. 1-48