Misc Language Features Features that were added relatively recently that are now in common use.

Slides:



Advertisements
Similar presentations
The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Advertisements

Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 17.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
Generics and the ArrayList Class
 2005 Pearson Education, Inc. All rights reserved Introduction.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Fall 2007CS 2251 Enum Types from Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
Lesson 5 Miscellaneous language features Swing Programming.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Moving up to Java 1.5 and Tomcat 5.5 Java Hour – Sept 23, 2005.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Working with arrays (we will use an array of double as example)
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
1 Enumerations and Structs Chapter 9. 2 Objectives You will be able to: Write programs that define and use enumeration variables. Write programs that.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Session 7 Methods Strings Constructors this Inheritance.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Object Oriented Programming in Java Lecture 14. Review Quiz 1. Write a method which gets an Object and call all its available ‘get’ Methods and print.
11-Jan-16 Bits and Pieces Some random things in Java.
Reviewing for Exam Lecture 12. Lab 1 Postfix.java –Hexadecimal Converting ‘a’ to number Converting ‘1’ to number –System.exit(3); Questions?
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
Classes, Interfaces and Packages
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
New Java Features Advanced Programming Techniques.
Seven Lecture Collection 1. 2 Some Legacy Collection Types  ArrayList  Enumeration  Vector  HashTable – self study.
OOP Tirgul 12.
Topic: Classes and Objects
Some random things in Java
Reviewing for Exam Lecture 1?.
Object Based Programming
Java Programming Language
(and a review of switch statements)
(and a review of switch statements)
Some random things in Java
More On Enumeration Types
Java Programming Language
Some random things in Java
CMPE212 – Reminders Course Web Site:
Java 5 New Features 1-May-19.
Presentation transcript:

Misc Language Features Features that were added relatively recently that are now in common use

Assertions Use the assert statement to insert assertions at particular points in the code. The assert statement can have one of two forms: –assert booleanExpression; –assert booleanExpression : errorMessage; The errorMessage is an optional string message that would be shown when an assertion fails.

Assertions Example: Simple check for rogue values Class Foo{ public void foo(int x[], int n){ assert n > 0 && n < x.length; “n out of range”; … } Example: Simple check for null object class Foo{ public void foo(){ Student s = StudentFactory.create(“Graduate”); assert s != null; }

Assertions Assertions are not typically used to signal errors in production client application code. Rather, they are used –During development –By library writers to signals errors to library users (who themselves are software developers!) java –ea | -da Program –(“enable assertions” or “disable assertions”)

foreach loop // Returns the sum of the elements of a int sum(int[] a) { int result = 0; for (int i : a) result += i; return result; } //Compare to old way int sum(int[] a) { int result = 0; for (int i = 0; i < a.length; ++i) result += a[i]; return result; } Much cleaner syntax! Think “for each i in the Collection a”

foreach with 2D Arrays for (int row = 0; row < a2.length; row++) { for (int col = 0; col < a2[row].length; col++) { output += " " + a2[row][col]; } output += "\n”; } for (int[] row : a2){ for (int val: row){ output += " " + a2[row][col]; } output += "\n”; }

foreach with Collections This ugly code for (Iterator i = suits.iterator(); i.hasNext(); ) { Suit suit = (Suit) i.next(); for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(suit, j.next())); } Can be replaced by … for (Suit suit : suits) for (Rank rank : ranks) sortedDeck.add(new Card(suit, rank)); Note however that the underlying Iterator is hidden, so only useful for moving through data, cannot delete, move backwards, etc.

Varargs Asa of 1.5 Java allows you to define/call methods with variable number of arguments. Before –void foo(int i, String[] args) was called as –String args[] = {“hello”, “goodbye”}; –foo(1, args); As of 1.5 it can also be called without the user having to create an array –void foo(int i, String… args) –foo(1,”hello”, “goodbye”); –foo(1, “my”, “name”, “is”, “Andrew”); –foo(1, “this”, “argument”, “list”, “can”, “be”, “any”, length”); This is not limited to Strings, any object and native types can be used as well.

Varargs Note that the vararg parameter, denoted by the ellipses (“…”), must always be the last one. Inside the method the … parameter is always handled as an array of whatever size. However, it can be called as a method with any number of arguments without having to box them in an array! This is really just a convenience, lying somewhere between overloading and forcing the user to create an array.

public class VarargsTest public static double average( double... numbers ){ double total = 0.0; // initialize total // calculate total using the enhanced for statement for ( double d : numbers ) total += d; return total / numbers.length; } public static void main( String args[] ) { double d1 = 10.0; double d2 = 20.0; double d3 = 30.0; double d4 = 40.0; System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", d1, d2, d3, d4 ); System.out.printf( "Average of d1 and d2 is %.1f\n", average( d1, d2 ) ); System.out.printf( "Average of d1, d2 and d3 is %.1f\n", average( d1, d2, d3 ) ); System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n", average( d1, d2, d3, d4 ) ); }

Static import In order to access static members, it is necessary to qualify references with the class they came from. For example –Math.cos(Math.PI * theta); Now, can avoid this with: –import static java.lang.Math.PI; –Import static java.lang.Math.* (to import all static members) Once the static members have been imported, they may be used without qualification: –double r = cos(PI * theta); Use sparingly!

Enumerated types A very useful technique to define integer types that can only store specific values (enforced by compiler) and can be referred to by useful names. Before enumerated types: –public static final int SEASON_WINTER = 0; –public static final int SEASON_SPRING = 1; –public static final int SEASON_SUMMER = 2; –public static final int SEASON_FALL = 3; New way: –enum Season {WINTER, SPRING, SUMMER, FALL }; –Season.Winter has a value of 0, Seaon.SPRING has a value of 1, …

New way Season now declares a new type that can only have the specified values! –Enhanced compiler-time checking possible –Also declares a namespace –In old way printed values are uninformative Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.

enum Month{JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC}; enum Season{WINTER,SPRING,SUMMER,FALL}; public class EnumTest{ public static void main(String[] args){ Season season = Meteorology.getMeteorologicalSeason(Month.JAN); System.out.println(season); } class Meteorology{ public static Season getMeteorologicalSeason(Month month){ //NOTE: unqualified name required in switch statement! switch(month){ case JAN: return Season.WINTER; case FEB: return Season.WINTER; //... default: return Season.SUMMER; }

Enumerated Types, cont. All enum types extend java.lang.enum (and thus not java.lang.Object!) Like classes enum types can be either public or default (package) scope Note that we can also set the internal integer values to anything we choose enum Season{Winter=3,SPRING=4, …}

More than meets the eye What has been discussed so far are the basics and include most of what is expected from enumerated types in other languages. However, in JavaEnumerated types also have many other cool high-level features that make them better than C enums –They can have fields and constructors –They can have methods –They can be looped over as collections –They can be looped over in ranges –They can be cloned –They can be printed See Enum.java in class examples

Adding methods to enum types public enum Season{ SUMMER, SPRING, FALL, WINTER; public String clothing(){ if (this == SUMMER) return("short sleeves"); else if (this == SPRING) return("Winter coat"); else if (this == FALL) return("long sleeves"); else if (this == WINTER) return("two winter coats"); return(null); } Note that enums Can be declared In their own classesscc For enums, “this” refers to the value of the operating Enumerated type (ie SUMMER, SPRING, etc.)

Enum properties, cont. enum types inheret a toString method that will give the String representation of the value of the elements > Season s = Season.WINTER; > String sval = s.toString(); > System.out.pritnln(sval) > WINTER Or just > System.out.println(s); enum types can be looped over as collections using the values method inherited from Enum –for (Season s : Season.values()) System.out.println(s);

No reason not to take this a step further and allow enumerated tyes to behave more like regular classes with fields, methods, constructors, etc. In fact this is possible (if not so common) enum Planet{ MERCURY (3.303e+23, e6), VENUS (4.869e+24, e6), EARTH (5.976e+24, e6), MARS (6.421e+23, e6), JUPITER (1.9e+27, e7), SATURN (5.688e+26, e7), URANUS (8.686e+25, e7), NEPTUNE (1.024e+26, e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } private double mass() { return mass; } private double radius() { return radius; } // universal gravitational constant (m3 kg-1 s-2) public static final double G = E-11; public double surfaceGravity() { return G * mass / (radius * radius); } public double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } Note that you cannot call the constructor in the regular way. It is private or package scope and is called internally These invoke constructor Semicolon required before fields/methods

C-style printing: printf method In 1.5 If C-style printing was added as a method on the PrintStream class: import java.io.*; public class PrintTest{ public static void main(String[] args){ float x = 1.2f; PrintStream p = new PrintStream(System.out); p.printf("%s: %f\n", "the result is", x); } Format statements can be very sophisticated.