11-Jan-16 Bits and Pieces Some random things in Java.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Everything You Ever Wanted To Know About Java O-O
9-Jun-14 Enum s (and a review of switch statements)
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
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.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Outline Java program structure Basic program elements
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
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.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
16-Jul-15 Java Versions of Java Java 1 Java 2 Java 5.0 Oak: Designed for embedded devices Java 1.1: Adds inner classes and a completely new event-handling.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
Prasadcs8841 Java 5 : New Features
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
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.
Effective Java: Generics Last Updated: Spring 2009.
The Java Programming Language
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
ArrayList, Multidimensional Arrays
CIT 590 Intro to Programming. logistics If you have not received a grade for calculator please send me your name and your partner’s name Please vote on.
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.
CIT 590 Intro to Programming First lecture on Java.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
1 Enumerations and Structs Chapter 9. 2 Objectives You will be able to: Write programs that define and use enumeration variables. Write programs that.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
OOP Basics Classes & Methods (c) IDMS/SQL News
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
New Java Features Advanced Programming Techniques.
Seven Lecture Collection 1. 2 Some Legacy Collection Types  ArrayList  Enumeration  Vector  HashTable – self study.
Java 1.5 New Features 22-Apr-18.
The need for Programming Languages
JAVA MULTIPLE CHOICE QUESTION.
Java Primer 1: Types, Classes and Operators
Some random things in Java
Generics A Brief Review 16-Nov-18.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Some random things in Java
Generics 27-Nov-18.
(and a review of switch statements)
(and a review of switch statements)
Some random things in Java
Introduction to Primitives
Some random things in Java
Java 5 New Features 1-May-19.
Generics 2-May-19.
Presentation transcript:

11-Jan-16 Bits and Pieces Some random things in Java

2 Versions of Java Java 1 Java 2 Java 5.0 Oak: Designed for embedded devices Java 1.1: Adds inner classes and a completely new event-handling model Java 1.2: Includes “Swing” but no new syntax Java 1.3: Additional methods and packages, but no new syntax Java 1.4: More additions and the assert statement Java 1.5: Generics, enums, new for loop, and other new syntax Java: Original, not very good version (but it had applets)

Using the command line Although we use Eclipse, everything can be done from the command line To compile all Java files in this directory: javac *.java javac is the Java compiler; it compiles.java files to.class files.class files are in a special, machine-independent language called Bytecode To run a program, where "MyProgram" is a Java file containing a main method, do: java MyProgram The java command invokes the Java Virtual Machine (JVM), which executes the Bytecode The above commands work if you have Java installed completely correctly, which usually means setting your CLASSPATH environment variable

4 Type wildcards Here’s a simple (no generics) method to print out any list: private void printList(List list) { for (Iterator i = list.iterator(); i.hasNext(); ) { System.out.println(i.next()); } } The above still works in Java 1.5, but now it generates warning messages Java 1.5 incorporates lint (like C lint ) to look for possible problems You should eliminate all errors and warnings in your final code, so you need to tell Java that any type is acceptable: private void printListOfStrings(List list) { for (Iterator i = list.iterator(); i.hasNext(); ) { System.out.println(i.next()); } }

Auto boxing and unboxing Java won’t let you use a primitive value where an object is required--you need a “wrapper” ArrayList myList = new ArrayList (); myList.add(new Integer(5)); Similarly, you can’t use an object where a primitive is required-- you need to “unwrap” it int n = ((Integer)myArrayList.get(2)).intValue(); Java 1.5 makes this automatic: myArrayList myList = new myArrayList (); myList.add(5); int n = myList.get(2); Other extensions make this as transparent as possible For example, control statements that previously required a boolean ( if, while, do-while ) can now take a Boolean There are some subtle issues with equality tests, though

Writing your own generic types public class Box { private List contents; public Box() { contents = new ArrayList (); } public void add(T thing) { contents.add(thing); } public T grab() { if (contents.size() > 0) return contents.remove(0); else return null; } Sun’s recommendation is to use single capital letters (such as T ) for types If you have more than a couple generic types, though, you should use better names

7 New methods in java.util.Arrays Java now has convenient methods for printing arrays: Arrays.toString( myArray ) for 1-dimensional arrays Arrays.deepToString( myArray ) for multidimensional arrays Java now has convenient methods for comparing arrays: Arrays.equals( myArray, myOtherArray ) for 1-dimensional arrays Arrays.deepEquals( myArray, myOtherArray ) for multidimensional arrays It is important to note that these methods do not override the public String toString() and public boolean equals(Object) instance methods inherited from Object The new methods are static methods of the java.util.Arrays class

8 Enumerations An enumeration, or “enum,” is simply a set of constants to represent various values Here’s the old way of doing it public final int SPRING = 0; public final int SUMMER = 1; public final int FALL = 2; public final int WINTER = 3; This is a nuisance, and is error prone as well Here’s the new way of doing it: enum Season { WINTER, SPRING, SUMMER, FALL }

9 enum s are classes An enum is actually a new type of class You can declare them as inner classes or outer classes You can declare variables of an enum type and get type safety and compile time checking Each declared value is an instance of the enum class Enums are implicitly public, static, and final You can compare enums with either equals or == enum s extend java.lang.Enum and implement java.lang.Comparable Hence, enums can be sorted Enums override toString() and provide valueOf() Example: Season season = Season.WINTER; System.out.println(season ); // prints WINTER season = Season.valueOf("SPRING"); // sets season to Season.SPRING

10 Advantages of the new enum Enums provide compile-time type safety int enums don't provide any type safety at all: season = 43; Enums provide a proper name space for the enumerated type With int enums you have to prefix the constants (for example, seasonWINTER or S_WINTER ) to get anything like a name space. Enums are robust If you add, remove, or reorder constants, you must recompile, and then everything is OK again Enum printed values are informative If you print an int enum you just see a number Because enums are objects, you can put them in collections Because enums are classes, you can add fields and methods

11 Enums really are classes  public enum Coin {  // enums can have instance variables private final int value;  // An enum can have a constructor, but it isn’t public Coin(int value) { this.value = value; }  // Each enum value you list really calls a constructor PENNY(1), NICKEL(5), DIME(10), QUARTER(25);  // And, of course, classes can have methods public int value() { return value; } }

12 Other features of enums values() returns an array of enum values Season[] seasonValues = Season.values(); switch statements can now work with enums switch (thisSeason) { case SUMMER:...; default:...} You must say case SUMMER:, not case Season.SUMMER: It’s still a very good idea to include a default case It is possible to define value-specific class bodies, so that each value has its own methods The syntax for this is weird, and I don’t yet understand it well enough myself to lecture on it

13 varargs You can create methods and constructors that take a variable number of arguments public void foo(int count, String... cards) { body } The “... ” means zero or more arguments (here, zero or more String s) Call with foo(13, "ace", "deuce", "trey"); Only the last argument can be a vararg To iterate over the variable arguments, use the new for loop: for (String card : cards) { loop body }

14 Static import facility import static org.iso.Physics.*; class Guacamole { public static void main(String[] args) { double molecules = AVOGADROS_NUMBER * moles;... } } You no longer have to say Physics.AVOGADROS_NUMBER Are you tired of typing System.out.println( something ); ? Do this instead: import static java.lang.System.out; out.println( something );

static Instance variables belong to instances—objects—belonging to the given class Each object has its own copy of these variables Instance methods are executed by those instances Within an instance method, the word this refers to the object that is executing the method Static variables belong to the class as a whole Static variables may be accessed by objects in that class, but… There is only one copy of each static variable, shared by all the objects Static methods belong to the class as a whole Static methods may be used by objects in that class, but… Static method cannot directly use instance variables (whose?), instance methods (who is executing it?), or the word this (to whom would it refer?)

Why would you ever use static ? Consider the method int gcd(int, int), which takes two integers and returns their Greatest Common Divisor This is a handy method to have when you are working with fractions, but why should you ask some particular fraction to do the work for you? int g = threeQuarters.gcd(x, y); It makes more sense to ask the class to do the work: int g = Fraction.gcd(x, y); The gcd method does not refer to any particular fraction, or any instance variables, or the word this – so it should be static

17 java.util.Formatter Java now has a way to produce formatted output, based on the C printf statement String line; int i = 1; while ((line = reader.readLine()) != null) { System.out.printf("Line %d: %s%n", i++, line); } Example specifications: %8d – decimal integer, 8 character positions %8.4f – floating point, 8 character positions, 4 after the decimal point %-20s – string, 20 character positions, left justified %6b -- boolean %n -- newline There are about 45 different format specifiers (such as %d and %s ), most of them for dates and times

18 Annotations In general code: Indicate that the method is supposed to override an inherited public boolean equals(Item other) {... } Gives a syntax error because the signature is wrong Indicate that the method should not be used in new code, because it has been replaced by something public int ancientMethod() { … } Eclipse will give you a warning (not an error) if you try to use this method Indicate that you know about the problem but are doing something type ) // Questionable code… You can create other kinds of annotations Various uses in JUnit and several others)

The End