Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Similar documents
Introduction to Programming Using Java (98-388)

JAVA WRAPPER CLASSES

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

15CS45 : OBJECT ORIENTED CONCEPTS

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

1 Shyam sir JAVA Notes

CSC Java Programming, Fall Java Data Types and Control Constructs

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

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

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

CS 231 Data Structures and Algorithms, Fall 2016

Formatting Output & Enumerated Types & Wrapper Classes

An overview of Java, Data types and variables

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

We now start exploring some key elements of the Java programming language and ways of performing I/O

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

Class Libraries and Packages

A variable is a name for a location in memory A variable must be declared

Index COPYRIGHTED MATERIAL

Packages. Examples of package names: points java.lang com.sun.security drawing.figures

Java Primer 1: Types, Classes and Operators

Java Language Features

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CT 229 Fundamentals of Java Syntax

Java Bytecode (binary file)

Chapter 4 Defining Classes I

Packages & Random and Math Classes

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Operators and Expressions

Getting started with Java

Using Classes and Objects. Chapter

Preview from Notesale.co.uk Page 9 of 108

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

CHAPTER 7 OBJECTS AND CLASSES

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

CST141 Thinking in Objects Page 1

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

5/23/2015. Core Java Syllabus. VikRam ShaRma

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Timing for Interfaces and Abstract Classes

JAVA: A Primer. By: Amrita Rajagopal

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

DM550 Introduction to Programming part 2. Jan Baumbach.

COMP 250 Winter 2011 Reading: Java background January 5, 2011

From C++ to Java. Duke CPS

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CHAPTER 7 OBJECTS AND CLASSES

PIC 20A The Basics of Java

20 Most Important Java Programming Interview Questions. Powered by

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

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Program Fundamentals

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

USING LIBRARY CLASSES

Java Programming. Atul Prakash

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

Brief Summary of Java

Interfaces (1/2) An interface forms a contract between the object and the outside world.

CSC 1214: Object-Oriented Programming

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Programming Language Concepts: Lecture 2

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Programming overview

OBJECT ORIENTED PROGRAMMING TYm. Allotted : 3 Hours Full Marks: 70

Another IS-A Relationship

Chapter 6 Introduction to Defining Classes

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Introduction to Java

Core Java Syllabus. Overview

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

CS260 Intro to Java & Android 03.Java Language Basics

Java Classes & Primitive Types

3. Java - Language Constructs I

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

1007 Imperative Programming Part II

Lab5. Wooseok Kim

Java Foundations Certified Junior Associate

Programming. Syntax and Semantics

Methods (Deitel chapter 6)

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

PESIT Bangalore South Campus

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Introduction to Java

Table of Contents Fast Track to Java 8 EVALUATIONA COPY

Pace University. Fundamental Concepts of CS121 1

Transcription:

Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries and the Java API 9/7/2007 3 1

Java API The Java programming language is defined by: 1. The essential features of the language (syntax) 2. A set of standard classes (e.g. String) used by most implementations of the language 3. A set of classes provided with an environment called the Java API (application programming interfaces) 9/7/2007 4 Java API Most of the Java API is written in terms of primitive language features. Some parts of the Java API are written in terms of the native operating system. 9/7/2007 5 The following program uses both essential language features and the API import java.lang.string; import java.io.filewriter; import java.io.ioexception; Qualified names public class test { public static void main(string[] args) { Standard classes try { FileWriter fw = new FileWriter("hello.txt"); String h = "Hello"; String w = "World"; fw.write(h + " " + w); fw.close(); catch (IOException e) { System.out.println("Error writing to file:" + e); Essential Language Features 9/7/2007 6 2

The Java API is organized into groups of related classes and interfaces called packages. A package defines a name space. The Java API (version 1.4.2) includes about 130 packages. To place a class inside a package, you add a package statement as the first statement of the source file package IT350program1 public class Student { 9/7/2007 7 Java Packages A class without a package statement is in the default package with no package name The full name of a class includes the package name followed by class name. For example: java.util.arraylist javax.swing.joptionpane 9/7/2007 8 Common Java Packages java.lang Includes Integer, String, StringBuffer, System, Runtime, etc. These are fundamental classes. Some of the classes even have support in the compiler and JVM. It is not necessary to import this package into the programs you write. This package is included automatically. 9/7/2007 9 3

Common Java Packages java.util Includes miscellaneous utility classes. includes collection classes such as Vector, Stack and LinkedList and other useful classes such as StringTokenizer andrandom. java.io Includes input and output classes. Two main categories: (1) streams (byte oriented I/O), and (2) readers and writers (Unicode or character I/O). 9/7/2007 10 Common Java Packages java.awt Includes original user interface control classes such as Button and TextField. Swing components have replaced some of the classes in this package, but most of the fundamental graphics classes in this package are still used. javax.swing The "swing" classes were added in Java 2. The swing package includes new classes such as JButton, JTextField, JApplet etc. java.applet Includes the Applet class and a few interfaces which are used to create applets. 9/7/2007 11 Importing Java Packages import all the classes in a package by using the wildcard character (*) import java.util.* //comment which class is being used The wildcard pertains only to class names for example, import classa.classb.*; will only import classes in the classa.classb package and NOT classes in a classa.classb.classc package, if there is one Or specify individual classes from a package: import.java.util.vector; This is the recommended style import.java.util.date; 9/7/2007 12 4

Importing Java Packages If you have several files for an application, you can use them all without writing import statements if they are in the same directory. Import statements are only needed if we are using classes that are not found in package java.lang and are not in our own (default) package. 9/7/2007 13 Feature Access Rules Access or visibility rules determine whether a method or a data variable can be accessed by another method in another class or subclass Instance variables & methods are contained in classes, which are contained in packages. To determine whether a field or method is accessible, Java starts by determining whether its containing package is accessible and then whether its containing class is accessible. 9/7/2007 14 Access Example public class Person{ private String ssn; //the only really private feature //the following attributes are public from the //perspective of other classes in the same package public String name; protected String address; int age; 9/7/2007 15 5

Visibility Making a class public does not have any effect on the visibility of its features. Private features are still private protected features are still protected 9/7/2007 16 Class Visibility Class access is public by default accessible if its package is accessible accessible only within its package. Declaring a class public means: if the package the class belongs to is imported into code belonging to some other package, then all public attributes and methods are public in the other package. (e.g. public class Vector in java.util) Features of a public class still have the same meaning. Private feature is still private, etc. 9/7/2007 17 Class Visibility If access designation is omitted from the class declaration, the class is package visible. The class is not visible from outside the package and cannot be referenced or instantiated from client code within another package. Class visibility is a form of encapsulation at the package level. Two or more classes can be placed in a single.java file (not recommended), but only one of the classes can be public. The public class s name must match the name of the file. 9/7/2007 18 6

Accessibility of Class Members public protected package private The class itself Yes Yes Yes Yes Classes in the Yes Yes Yes No same package Subclasses in a Yes Yes No No different package Non-subclasses in Yes No No No a different package 9/7/2007 19 Revisiting Strings as Objects Strings are created in two ways: String name = Judy ; String name = new String( Judy ); in the first case, the string is stored in a literal pool which is shared if you use the same String literal in different places in the code. in the second case, a different instance of the string is created with every call to new, even if there is already a string with the same literal value in the application. 9/7/2007 20 String class methods Besides length(), there are other useful methods in the String class: String s = banana split ; if(s.startswith( ba )) //evaluates to true if(s.endswith( it )) //evaluates to true int i = s.indexof( nan ); //i will equal 2 String j = it ; int k = s.indexof(j); //k will equal 10; System.out.println(s.indexOf( spil ); //prints -1 9/7/2007 21 7

String class methods String replace(char old, char new); String s = x1 x2 x3 ; String y = s.replace( x, y ); String s is unchanged; String y is y1 y2 y3 String substring(int); String s = banana split ; String t = s.substring(7); //t is now reference to split String substring(int, int); String s = banana split ; String t = s.substring(9,12); //t is reference to lit 9/7/2007 22 String objects Strings are immutable. When you think you are modifying a String object by concatenating another String object to it, you are actually creating a new string object -- making the old String object inaccessible by reference. String s = banana ; s = s + split ; banana bananasplit s no longer accessible s 9/7/2007 23 Wrapper Classes The wrapper classes are primarily used to store primitive data types in objects so they can be handled by classes that only work with objects. For example, the Java Collections API has many data structure classes such as ArrayList and HashMap that only work with objects in order to store a primitive number in one of these collections, you must first wrap it. 9/7/2007 24 8

Wrapper Classes A wrapper class is provided for each primitive data type. Wrappers encapsulate methods that can be used to perform certain data conversions. The wrapper class integer has a method parseint() that converts a String into an int: int x = parseint( 350 ); parseint() is used to handle numeric input Wrapper classes include Boolean, Character, Byte, Short, integer,long, Float and Double 9/7/2007 25 Wrapper Classes Storing integers in a Vector object Simple data types cannot be stored in a container object because containers hold Object type elements, and simple data types are not Object types. To store integers in a Vector object, we build an object wrapper around each int value and add the object wrapper to the vector instead of the int itself. v.add(new Integer(age)); //wrap age in Integer 9/7/2007 26 Autoboxing Syntact shortcut added to java 5.0 autoboxing -- automatically converting primitives to wrappers To autobox, just assign a primitive value to an appropriate wrapper object auto-unboxing -- automatically converting wrappers to numbers To auto-unbox, assign a wrapper object reference to an appropriate primitive variable Integer a = 37; //autobox int to Integer float f = new Float(15.5f); //auto-unbox Float to float long l = a; //auto-unbox Integer to long 9/7/2007 27 9

Using Wrapper Classes to Store integers in a Vector object //code by Jacquie Barker, modified by Judy Mullins import java.util.* //for Vector public class VectorTest { public static void main(string[] args) { Vector v = new Vector(); //container of integers for (int i = 0; i < 10; i++) { Integer intwrapper = new Integer(i); v.add(intwrapper); for (int i = 0; i<10; i++) { Integer intwrapper = (Integer) v.elementat(i); Sysem.out.println ( intwrapper.intvalue() ); 9/7/2007 28 Using Autoboxing in a Vector object //code by Judy Mullins import java.util.* //for Vector public class VectorTest { public static void main(string[] args) { Vector<Integer> v = new Vector<Integer>(); //container of integers for (int i = 0; i < 10; i++) { v.add(i); for(int value : v) System.out.println(value); 9/7/2007 29 Converting bet. numbers and strings int Integer.parseInt(String); converts the String argument to an int if the argument is a valid integer, else a NumberFormatException is thrown: public class integertest{ public static void main(string [] args) { String[] ints = { 123, 456, hello ; try { for (int i=0; i < ints.length; i++) { int test = Integer.parseInt(ints[i]); System.out.println( test + converted ok ); catch (NumberFormatException e) { System.out.println( ints[i] + is invalid integer ); 9/7/2007 30 10

Converting bet. numbers and strings String Integer.toString(int) turns an integer into a String int j = 9; String s = Integer.toString(j); //s equals 9 Easier way to do the same thing: int j = 9; String s = + j;//concatenate empty string with int. //The int will automatically be // changed to a String 9/7/2007 31 Class Modifiers public Accessible everywhere. One public class allowed per file. The file must be named ClassName.java private Only accessible within a file <empty> Accessible within the current class package. abstract A class that contains abstract methods final No subclasses 9/7/2007 32 Method and Field Modifiers For both methods and fields public protected private static final For methods only abstract synchronized native For fields only volatile transient 9/7/2007 33 11

final Variables Final variables are named constants. class CircleStuff { static final double pi =3.1416; Final variables are also static. 9/7/2007 34 Hello World Revisited Details about this little program 9/7/2007 35 Hello World /* 1 */ // My first Java program /* 2 */ import java.lang.*; //optional import /* 3 */ public class HelloWorld { /* 4 */ public static void main(string[] args) { /* 5 */ System.out.println("Hello World!"); /* 6 */ /* 7 */ Note: Line numbers are NOT part of the java program. 9/7/2007 36 12

Class containing main() method is considered the application driver Entry point for the class: public static void main(string[] args) The class name must match exactly (i.e. case) the name of the external file containing the source code of the class. 9/7/2007 37 The main() method has two responsibilities 1. Instantiate the core objects needed for the program 2. Display the start-up window of the GUI of an application, if it has one 9/7/2007 38 Why is the main() method declared static? A static method can be invoked on a class even if no instance of the class has been created. When the JVM loads the class with the main method, no objects exist yet because the main() method, which starts the instantiation process, hasn t been executed yet! After executing main(), the JVM loads additional classes as needed when referenced by the application. 9/7/2007 39 13

Static Methods A static method (class method) can be invoked on either an instance or a class as a whole. public class Student { public static int totalstudentcount; public static void incrementtotalcount() { totalstudentcount++;) //in main program: Student.incrementTotalCount(); Student s1=new Student(); s1.incrementtotalcount(); 9/7/2007 40 Static Methods A static method can only access static attributes and invoke other static methods The this keyword has no meaning within a static method we can t know for sure that there will be an instance of an object to self-reference 9/7/2007 41 Static Attributes A static attribute is shared by all instances of a class. It does not belong to any one instance or object of the class for which it is declared. one per class, rather than one per object. Counters are often declared static public class Student { public static int totalstudentcount = 0; //opt. Initialization 9/7/2007 42 14

Static Attributes When any object of the class modifies a static attribute, the new value applies to all objects Student s1 = new Student(); Student s2 = new Student(); s1.totalstudentcount++; class s2.totalstudentcount++; // 1 student for the // now 2 students 9/7/2007 43 Static Attributes The value of the static attribute can be accessed by the class using the dot notation Student.totalStudentCount++; System.out.println(Student.totalStudentCount); Class name Class name 9/7/2007 44 Static Attributes Static attributes are also called class variables or instance variables Common usage: to make data globally available to an application Class variables are uncommon more common is to define constants public static final double PI = 3.14159265358979323846 9/7/2007 45 15

Class Declaration Example public class Point { public int x, y; public void move(int dx, int dy) { x += dx; y += dy; Point point1; // Point not created Point point2 = new Point(); point1 = point2; point1 = null; x and y are initialized to their default initial values. 9/7/2007 46 Explicit Initializer public class Point { public int x = 0, y = 0; public void move(int dx, int dy) { x += dx; y += dy; Point point1 = new Point(); // (0,0) 9/7/2007 47 Constructors public class Point { public int x, y; public Point() { // no-arg x = 0; y = 0; public Point(int x0, int y0) { x = x0; y = y0; Point point1 = new Point(); // no-arg Point point2 = new Point(20, 20); Constructors are invoked after default initial values are assigned. No-arg constructor is provided as a default when no other constructors are provided. 9/7/2007 48 16

Resources for further reading About Java language features: http://java.sun.com/docs/white/langenv/ About Java technology: http://java.sun.com/docs/books/tutorial/getstarted/intro/d efinition.html Quick introduction to Java programming: http://java.sun.com/docs/books/tutorial/getstarted/index. html All the language fundamentals: http://java.sun.com/docs/books/tutorial/java/index.html 9/7/2007 49 17