CS/ENGRD 2110 SPRING 2013 Lecture 2: Introduction to Java 1.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Written by: Dr. JJ Shepherd
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Access to Names Namespaces, Scopes, Access privileges.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Primitive Data Types byte, short, int, long float, double char boolean Are all primitive data types. Primitive data types always start with a small letter.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
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.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Introduction to Methods
Hello AP Computer Science!. What are some of the things that you have used computers for?
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
LESSON 2 CREATING A JAVA APPLICATION JAVA PROGRAMMING Compiled By: Edwin O. Okech [Tutor, Amoud University]
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.
The Java Programming Language
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
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.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Procedural programming in Java Methods, parameters and return values.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programs and Classes A program is made up from classes Classes may be grouped into packages A class has two parts static parts exist independently Non-static.
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
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.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Working With Objects Tonga Institute of Higher Education.
Hello Computer Science!. Below is an example of a Hello World program in JAVA. While it is only three lines of code, there are many things that are happening.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Written by: Dr. JJ Shepherd
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
OOP Basics Classes & Methods (c) IDMS/SQL News
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
CS 106 Introduction to Computer Science I 01 / 24 / 2007 Instructor: Michael Eckmann.
Object Oriented Programming Lecture 2: BallWorld.
A High Flying Overview CS139 – Fall 2010 How far we have come.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Information and Computer Sciences University of Hawaii, Manoa
Some Eclipse shortcuts
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Programmazione I a.a. 2017/2018.
5 Variables, Data Types.
An Introduction to Java – Part I, language basics
Namespaces, Scopes, Access privileges
Applying OO Concepts Using Java
Object Oriented Programming in java
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming Language
In this class, we will cover:
Classes, Objects and Methods
Presentation transcript:

CS/ENGRD 2110 SPRING 2013 Lecture 2: Introduction to Java 1

Java 2  The basic language looks much as you would expect from other languages : if, else, for, while, x= x+1; …  Braces { } around blocks of code  Functions: as in int areaOfCircle(double r) { return Math.PI * r * r; }  Variable declarations: int k; (other primitive types: double, char, byte …) Circle c; (where Circle is a class) double[ ] b; (b can contain an array of double values)  Exceptions: “thrown” when something bad occurs (like dividing by zero or indexing off the end of an array). There is a way to “catch” such events.

A first surprise 3  In some languages, allocation is “automatic” double[ ] b; Circle c; ... not in Java. These declarations created two useable variables, but neither is initialized.  In Java, object creation is explicit: b = new double[100]; c = new Circle(2.7651);

Hello World! 4 /** A simple program that prints Hello, world! ken * */ public class myClass { /** void main(String[ ] args): Starting point for my program args Command line arguments */ public static void main(String[ ] args) { // At this point main is executing. We’ll just print “hello" System.out.println("Hello, world!"); } Example of a JavaDoc comment A Java program consists of a set of classes. This class is called myClass The class is public, meaning that its contents are accessible from code running in other classes This JavaDoc comment says that the method that follows has a parameter named “args”. In fact we should fill in more information for the whole method myClass has a single method called main. main belongs to class myClass. Later we will see non-static methods that belong to individual object instances. In Java we normally use lower-case for method names When the program is launched, one can specify arguments on the command line (Eclipse has a page for that). Here, the argument is an array of Strings System is a class in package java.lang. System has a static variable out, which is an object with a public method println. It prints a string on the console Class System is in package java.lang and doesn’t need an import statement, but for other classes we would have been required to put an import statement at the top of the file after the initial comment. Eclipse can sometimes guess what class you had in mind and will offer to insert the needed import statement for you.

Hello World! 5 /** A simple program that prints Hello, world! ken * */ public class myClass { /** void main(String[ ] args): Starting point for my program args Command line arguments */ public static void main(String[ ] args) { // At this point main is executing. We’ll just print “hello" System.out.println("Hello, world!"); }

An introduction to Java and objects 6  Some Java features seen in our example:  Packages contain classes that contain code Here java.lang is such a package, which is always accessible As noted, normally you need to “import” each package, but not java.lang  Variables always have specified “types” For example, parameter arg of main has type String[ ] Use arg.Length is the length of the vector In Java, you are forced to be very precise about what kinds of value each variable can hold

An introduction to Java and objects 7  Some Java features already seen in our example:  Packages contain classes  Variables have specified “types”  A type is a set of values together with operations on them  Methods like main and println main is static method of class myClass out is a static variable of class System Method out.println is a method associated with object out. Eclipse knew which methods object out contains because it knows the type of out, which is PrintStream

More things to notice 8  Lots of curly braces  Indentation reflects program structure  Eclipse is your helper in code development  When you start to type, it guesses what you are trying to do and offers to fill things in  Eclipse knows about the methods you can use in the objects you are working with  And it can automatically help with things like indentation, although you can override its help

Java won’t notice certain mistakes 9  What does this do? n = 0; while(n = 0); n = n+1; Oops  What does this do? n = 0; while(n = 0); n = n+1; ... this code is an infinite loop, stuck on the “while” stmt. Java doesn’t pay attention to indentation...

What are “classes” 10  In Java we distinguish between two kinds of variable  Variables declared with “primitive” types like int, double. Notice the lower-case type names.  Variables that contain a pointer to an object, or might contain null if no assignment has been done yet.  A class defines a new type of object  It tells the value of the object, the operations you can do on it, how to initialize a new instance, etc.  We use upper-case names for class types

int and Integer are not the same! 11  int x, y;  x = 77;  y = x;  Integer x, y;  x = new Integer(77);  y = x; Variables x and y are of type int, which is a primitive type. x and y each contain one value of type int. Variables x and y are “references”: they can contain a pointer to an object of type Integer, which is a class. Variable nameValue x77 y Variable nameValue y 77

Auto-boxing, unboxing 12  Integer is what we call a “wrapper” class:  It is predefined as a class containing an int value field  All the normal int operations work, but an instance of Integer is an object, so object operations also work.  In contrast, an int is a base type, not an object  Autoboxing/unboxing  In any situation where you need an int, Java will allow an Integer. It automatically “auto-unboxes” the int  In a situation where you need an Integer and supply an int, Java will “auto-box” the int by creating an Integer object

What’s in x before the new? 13 Integer x, y; x = new Integer(77);  The answer depends on where we declared the variable.  If x is a local variable, it was undefined before the first value was assigned to it. Trying to access an undefined variable is illegal; your code won’t compile  If x is a field in a class, its initial value is null Means that x doesn’t point to an object instance If you try to reference a component of x (e.g. x.value, you get an exception and the program crashes. Java has 4 kinds of variables: 1.FIeld (of an object) 2.class variable (declared as a field but with the static modifier) 3.parameter of a method 4.local variable – declared within a method body.

Reference variables “point” to objects! 14  A reference variable can’t point to an object until you assign an object reference to it!  All objects are created using the new-expression. x y value 77 x= new Integer(77);y= x;

Reference variables “point” to objects! 15  We ended up with two names for a single object!  It was created by execution of x = new Integer(77);  y is a second way to reference this same object  The value 77 lives inside the object, in a field that has primitive type int.  int and Integer are not the same! x y value 77

Classes and object instances 16  A class defines a type of objects.  Java predefines some classes, like System and Integer  Each object has a type, which is the name of the class that was instantiated to create it  Create an object using the new-expression, as in: Integer x = new Integer(77); Toy t1 = new myLittlePony(“Apple Bloom”);

What’s in an object of a class? 17  An object contains fields  These are variables that live within each object  Each variable has a type, a name, and an initial value  We can control access private field: can be accessed only inside the class public field: can be accessed from outside the class. Software engineering principle: Make most fields private. Reason for the principle will become clear as the course progresses.

What’s in an object of a class? 18  An object also contains methods  Functions (return values) or procedures (do something but return nothing, indicated by void)  There is a way to associate them with operators For example you could define “+” to call “Add”…  You can define the same function name multiple times with different parameter types

What’s in an object of a class? 19  Every class has a “constructor”  A method with the same name as the class  Its job is to initialize the class variables  If omitted, Java puts in this constructor: public class-name() {} It has no parameters. It does nothing, but very fast.  Expression new C(args) 1. Create object of class C somewhere in memory 2. Execute constructor call C(args) 3. Result: a pointer to an intialized “C” object Note: earlier we used the notation for such pointers

Some slightly fancy things 20  We like “getter” and “setter” methods  public field: assignments to it could break the logic  private field: provide public methods to get/set the value of the field and check consistency  Set/Get methods ensure that invariants are maintained.  Suppose class Circle has fields: private double radius, circum;  Make sure they are non-negative  Maintain the invariant circum = 2*pi*radius  If the fields were public, mistakes might sneak in

! books.google.com/ngrams Let’s create a simple demo program 21  Count the number of lines and characters in the file  Fancier: could have it count the words, or make a list of words and the number of occurances of each, or even short phrases.  We could use this to do cutting edge research, answering questions like: When was “wrong in so many ways” first used?  We’ll use a predefined class FileStream  I found it using “Google” but focused on the information from Java.Oracle.com  Once I found it, I decided to reuse this existing class rather than try to build one of my own.  In CS2110, using prebuilt Java technology is encouraged but we limit ourselves to Java.Oracle.com

(Switch to Eclipse now) 22 Ken posted some little videos of him running Eclipse to solve a little sample problem