Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.

Slides:



Advertisements
Similar presentations
Basic Java Constructs and Data Types – Nuts and Bolts
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 63 – Manipulating Data Using Methods – Day 2.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Lecture 2: Object Oriented Programming I
Expressions ► An expression can be a single variable, or can include a series of variables. If an expression includes multiple variables they are combined.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
Some basic I/O.
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 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
Review Java.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
Programming in Java; Instructor:Moorthy Introduction, Objects, Classes, Libraries1 Programming in Java Introduction.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
1 Course Lectures Available on line:
Java and C++, The Difference An introduction Unit - 00.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 4.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
From C++ to Java A whirlwind tour of Java for C++ programmers.
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.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
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.
Copyright Curt Hill Variables What are they? Why do we need them?
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSC Java Programming, Spring, 2010 Week 2: Java Data Types, Control Constructs, and their C++ counterparts.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Object Oriented Programming Lecture 2: BallWorld.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 7 User-Defined Methods.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
2.5 Another Java Application: Adding Integers
Objects, Classes, Program Constructs
I/O Basics.
CMSC 202 Static Methods.
An Introduction to Java – Part I, language basics
Classes and Objects 5th Lecture
IFS410 Advanced Analysis and Design
Java Programming Language
Presentation transcript:

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs2 Program Structure/Environment  Java –Is interpreted (C/C++ are Compiled) –No Preprocessor –No #define, #ifdef, #include,...  Main method (for Java applications) –Embedded in a Class public class Xyz { public static void main (String args[]) { … } –Each class can define its own main method –Program’s starting point depends on how the interpreter is invoked. $ java Xyz

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs3 Command Line Arguments  Command Line Args are passed to main method public class Echo { // From JEIN public static void main(String argv[]) { for (int i=0; i<argv.length; i++) System.out.print(argv[i] + ” ”); System.out.print("\n"); System.exit(0); }  main has a return type of void (not int )  The System.exit method is used to return value back to OS  The length property is used to return array size

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs4 For Statement  Java’s for stmt is similar to C/C++, except:  Comma operator is simulated in Java for (i=0, j=0; (i<10) && (j<20); i++, j++) { … } –Allowed in initialization and test sections –Makes Java syntactically closer to C  Variable declaration –variables can be declared within for statement, but can’t be overloaded … int i; for (int i=0; i<n; i++) { … } // Not valid in Java –declaration is all or nothing for (int i=0, j=0; … ) // Declares both i and j  Conditional must evaluate to a boolean –Also true for if, while

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs5 If, While, Do While, Switch  These are (essentially) the same as C/C++ if (x != 2) y=3; if (x == 3) y=7; else y=8; if (x >= 4) { y=2; k=3; } while (x<100) { System.out.println ("X=" + x); x *= 2; } do { System.out.println ("X=" + x); x *= 2; } char c;... switch (c) { case 'Q': return; case 'E': process_edit(); break; default: System.out.println ("Error"); }

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs6 Name Space  No globals  variables, functions, methods, constants  Scope  Every variable, function, method, constant belongs to a Class  Every class is part of a Package  Fully qualified name of variable or method.. –Packages translate to directories in the “class path” –A package name can contain multiple components java.lang.String.substring() COM.Ora.writers.david.widgets.Barchart.display() - This class would be in the directory “XXX/COM/Ora/writers/david/widgets”, where XXX is a directory in the “class path”

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs7 Package; Import  Package Statement –Specifies the name of the package to which a class belongs package Simple_IO; // Must be the first statement public class Reader { … } –Optional  Import Statement –Without an import statement java.util.Calendar c1; –After the import statement import java.util.Calendar;... Calendar c1; –Saves typing import java.util.*;// Imports all classes

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs8 Access Rules  Packages are accessible –If associated files and directories exist and have read permission  Classes and interfaces of a package are accessible –From any other class in the same package –Public classes are visible from other packages  Members of a class (C) are accessible –[Default] From any class in the same package –Private members are accessible only from C –Protected members are accessible from C and subclasses of C –Public members are accessible from any class that can access C  Local variables declared within a method –Are not accessible outside the local scope

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs9 Data Types  Primitive Types  Integral ( byte, short, char, int, long ) –char is unsigned and also used for characters  Floating Point ( float, double )  boolean  Classes  Predefined classes –String, BigInteger, Calendar, Date, Vector,... –Wrapper classes (Byte, Short, Integer, Long, Character)  User defined classes  "Special" classes –Arrays

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs10 Expressions  Arithmetic expressions in Java are similar to C/C++  Example int i = / % 3 = 5 + (12 / 5) - (10 % 3) = = 6 –Operators cannot be overloaded in Java –Integer division vs. floating point division –Operator precedence

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs11 Objects  Objects  Instances of classes are called objects  Object variables store the address of an object –Different from primitive variables (which store the actual value) –Primitive Data Type example int i=3; int j=i; i=2;// i==2; j==3 –Object Example1 java.awt.Button b1 = new java.awt.Button("OK"); java.awt.Button b2 = b1; b2.setLabel("Cancel"); // Change is visible via b1 also b1 = new java.awt.Button("Cancel")  No explicit dereferencing (i.e., no &, * or -> operators) –No pointers –null = "Absence of reference" = a variable not pointing to an object

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs12 Objects are handled by Reference  Objects in Java are handled "by reference"  Comparison is by reference –Following is true if b1, b2 point to the same object if (b1 == b2) { … } if (b1.equals(b2)) { … } // member by member comparison  Assignment copies the reference b1 = b2; b1.clone(b2); // Convention for copying an object  Parameters passing is always by value  The value is always copied into the method  For objects, the reference is copied (passed by value) –The object itself is not copied –It is possible to change the original object via the reference

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs13 Parameter Passing Example class ParameterPassingExample { static public void main (String[] args) { int ai = 99; StringBuffer as1 = new StringBuffer("Hello"); StringBuffer as2 = new StringBuffer("World"); System.out.println ("Before Call: " + show(ai, as1, as2)); set(ai,as1,as2); System.out.println ("After Call: " + show(ai, as1, as2)); } static void set (int fi, StringBuffer fs1, StringBuffer fs2) { System.out.println ("Before Change: " + show(fi, fs1, fs2)); fi=1; fs1.append(", World"); fs2 = new StringBuffer("Hello, World"); System.out.println ("After Change: " + show(fi, fs1, fs2)); } static String show (int i, StringBuffer s1, StringBuffer s2) { return "i=" + i + "s1='" + s1 + "'; s2='" + s2 + "'"; }

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs14 Constants  Constants  Value of variable is not allowed to change after initialization –Example final double PI = ; –Initialization can be done after declaration final boolean debug_mode; … if (x<20) debug_mode = true; // Legal else debug_mode = false; // Legal … debug_mode = false; // Error is caught at compile time –Value of variable cannot change; value of object can change final Button p = new Button("OK"); p = new Button ("OK"); // Illegal. P cannot point to // a different object p.setLabel ("Cancel"); // Legal.

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs15 Input/Output  java.io.OutputStream - A byte output stream –System.out (C:stdout; C++:cout) –System.err (C:stderr; C++:cerr)  Convenience methods: print, println –send characters to output streams  java.io.InputStream - A byte input stream –System.in (C:stdin; C++:cin)  InputStreamReader –Reads bytes and converts them to Unicode characters  BufferedReader –Buffers input, improves efficiency –Convenience method: readLine() InputStreamReader isr = new InputStreamReader(System.in); BufferedReader stdin = new BufferedReader (isr); String s1 = stdin.readLine();

Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs16 Echo.java –A version of Echo that reads in data from System.in import java.io.*; class Echo { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); String message; System.out.println ("Enter a line of text:"); message = stdin.readLine(); System.out.println ("Entered: \"" + message + "\""); } // method main } // class Echo –java.lang.Integer.parseInt converts a string to an integer int message_as_int = Integer.parseInt(message); –java.io.StreamTokenizer handles more advanced parsing