Java Programming Tutorial 1

Similar documents
Lesson: Classes and Objects

CS260 Intro to Java & Android 03.Java Language Basics

Universiti Malaysia Perlis

Inheritance, part 2: Subclassing. COMP 401, Spring 2015 Lecture 8 2/3/2015

Java Primer 1: Types, Classes and Operators

Lecture 2: Java & Javadoc

Inheritance. The Java Platform Class Hierarchy

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Computer Science 210: Data Structures

Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

Full file at

Introduction to Programming Using Java (98-388)

CS 231 Data Structures and Algorithms, Fall 2016

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java OOP (SE Tutorials: Learning the Java Language Trail : Object-Oriented Programming Concepts Lesson )

Introduction and Review of Java: Part 2

Chapter 6 Introduction to Defining Classes

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

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

Java Bytecode (binary file)

Pace University. Fundamental Concepts of CS121 1

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

Short Notes of CS201

Sri Vidya College of Engineering & Technology

CS201 - Introduction to Programming Glossary By

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Tony Valderrama, SIPB IAP 2009

Programming overview

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

What is the output of the following code segment:

Language Reference Manual

Program Correctness and Efficiency. Chapter 2

Chapter 2 Author Notes

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java Style Guide. 1.0 General. 2.0 Visual Layout. Dr Caffeine

IT 374 C# and Applications/ IT695 C# Data Structures

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

CSE 142 Su 04 Computer Programming 1 - Java. Objects

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

CMSC 132: Object-Oriented Programming II

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

1 Lexical Considerations

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Index COPYRIGHTED MATERIAL

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Key Differences Between Python and Java

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Lecture 02, Fall 2018 Friday September 7

STRUCTURING OF PROGRAM

Fundamental Concepts and Definitions

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

13 th Windsor Regional Secondary School Computer Programming Competition

CS201 Some Important Definitions

Lexical Considerations

Comments are almost like C++

The SPL Programming Language Reference Manual

Decaf Language Reference Manual

Lexical Considerations

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CS201 Latest Solved MCQs

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Course Outline. Introduction to java

Definition of DJ (Diminished Java)

Expanded Guidelines on Programming Style and Documentation

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Basics of Java Programming

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

20 Most Important Java Programming Interview Questions. Powered by

1/16/2013. Program Structure. Language Basics. Selection/Iteration Statements. Useful Java Classes. Text/File Input and Output.

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

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

The Java Programming Language

Data Structure. Recitation IV

Module 10 Inheritance, Virtual Functions, and Polymorphism

Brief Summary of Java

Lecture 10 Declarations and Scope

UNIT- 3 Introduction to C++

Cpt S 122 Data Structures. Introduction to C++ Part II

Program Fundamentals

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

11 Coding Standards CERTIFICATION OBJECTIVES. Use Sun Java Coding Standards

1 Shyam sir JAVA Notes

Chapter 2 Basic Elements of C++

CS11 Java. Fall Lecture 1

Review sheet for Final Exam (List of objectives for this course)

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Lab # 2. For today s lab:

corgi Language Reference Manual COMS W4115

Defining Classes and Methods

Chapter 4 Java Language Fundamentals

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Transcription:

Java Programming Tutorial 1

Every programming language has two defining characteristics: Syntax Semantics

Programming Writing code with good style also provides the following benefits: It improves the readability, consistency, and homogeneity of the code, which makes it easier to understand and maintain. It makes the code easier to trace and debug, because it's clear and consistent. It allows you to continue more easily where you or another programmer stopped, particularly after a long period of time. It increases the benefit of code walkthroughs, because the participants can focus more on what the code is doing.

General Guidelines: Writing Java with good style is not hard, but it does require attention to detail. Here are some general guidelines to follow: Make the code clear and easy to read. Make the code consistent. Use obvious identifier names. Logically organize your files and classes. Have only one class per file (not including inner classes). Use a maximum line width of 80-90 characters. Use whitespace and/or other separators judiciously. Use spaces instead of tabs for indentation.

The Java language supports three kinds of comments: /* text */ The compiler ignores everything from /* to */. /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc, see the Java tool documentation. // text The compiler ignores everything from // to the end of the line.

Comments There are two type of comments that you can put in your Java code: Javadoc comments (also called documentation comments) and implementation comments. Javadoc comments can be extracted by the javadoc tool to produce API documentation. Implementation comments are those comments that explain the how and why of the code. Use Also, keep in mind that good comments are helpful; bad comments are a nuisance. Example 1. Bad Comment Style // applyrotascii() -- Apply ASCII ROT private void applyrotascii(){ try{ int rotlength = Integer.parseInt(rotationLengthField.getText().trim()); // get rot len RotAscii cipher = new RotAscii(rotLength); // new cipher textarea.settext(cipher.transform(textarea.gettext())); // transform catch(exception ex){ /* Show exception */ ExceptionDialog.show(this, "Invalid rotation length: ", ex);

Example 2. Good Comment Style. /** * Apply the ASCII rotation cipher to the user's text. The length is retrieved * from the rotation length field, and the user's text is retrieved from the * text area. * * @author Thornton Rose */ private void applyrotascii() { int rotlength = 0; // rotation length RotAscii cipher = null; // ASCII rotation cipher try { // Get rotation length field and convert to integer. rotlength = Integer.parseInt(rotationLengthField.getText().trim()); // Create ASCII rotation cipher and transform the user's text with it. cipher = new RotAscii(rotLength); textarea.settext(cipher.transform(textarea.gettext())); catch(exception ex) { // Report the exception to the user. ExceptionDialog.show(this, "Invalid rotation length: ", ex);

Blocks and Statements Use the following guidelines for writing blocks and statements: Put only one statement per line. Always use braces with control statements (e.g., 'if'). Consider marking the end of a block with a comment (e.g., // end if), particularly with long or nested blocks. Put variable declarations at the beginning of a block. Always initialize variables.. Indent the case clauses in a switch block. Put whitespace before and after operators. In if, for, or while, put whitespace before the "(". Use whitespace and parentheses in expressions to increase readability.

Example 3. Bad Block Style. try{ for(int i=0;i<5;i++){... int threshold=calculatethreshold(); float variance=(threshold*2.8)-1; int c=0; if (threshold<=15) c=calculatecoefficient(); switch(c){ case 1: setceiling(c*2); break; case 2: setceiling(c*3); break; else: freakout(); catch(exception ex){...

Example 4. Good Block Style. try { int threshold = 0; float variance = 0.0; int coefficient = 0; // Prepare 5 cycles. for (int i = 0; i < 5; i ++){ preparecycle(i); // Calculate the threshold and variance. threshold = calculatethreshold(); variance = (threshold * 2.8) - 1; // If the threshold is less than the maximum, calculate the coefficient. // Otherwise, throw an exception. if (threshold <= MAX_THRESHOLD) { coefficient = calculatecoefficient(); else { throw new RuntimeException("Threshold exceeded!"); // Set the ceiling based on the coefficient. switch (coefficient) { case 1: setceiling(coefficient * 2); break; case 2: setceiling(coefficient * 3); break; else: freakout(); // end switch

Bytecode Programming code that, once compiled, is run through a virtual machine instead of the computer's processor. By using this approach, source code can be run on any platform once it has been compiled and run through the virtual machine. Bytecode is the compiled format for Java programs. Once a Java program has been converted to bytecode, it can be transferred across a network and executed by Java Virtual Machine (JVM). Bytecode files generally have a.class extension.

JVM A Java virtual machine (JVM), an implementation of the Java Virtual Machine Specification, interprets compiled Java binary code (called bytecode) for a computer's processor (or "hardware platform") so that it can perform a Java program's instructions. Java was designed to allow application programs to be built that could be run on any platform without having to be rewritten or recompiled by the programmer for each separate platform. A Java virtual machine makes this possible because it is aware of the specific instruction lengths and other particularities of the platform. The Java Virtual Machine Specification defines an abstract -- rather than a real -- machine or processor. The Specification specifies an instruction set, a set of registers, a stack, a "garbage heap," and a method area. Once a Java virtual machine has been implemented for a given platform, any Java program (which, after compilation, is called bytecode) can run on that platform. A Java virtual machine can either interpret the bytecode one instruction at a time (mapping it to a real processor instruction) or the bytecode can be compiled further for the real processor using what is called a just-in-time compiler.

Object-Oriented Programming Concepts Object: is an instance of a class Class: is a template for an object Inheritance: allows the creation of hierarchical classification class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here Interface: allows a set of methods to be implemented by one or more classes class ACMEBicycle implements Bicycle { // remainder of this class implemented as before Package: a namespace for organizing related classes and interfaces in a logical manner

Class Definition Every Java program is defined as a class. A class is a collection of data, stored in named fields, and coded, organized into named methods, that operates on that data. The fields and methods are called members of a class. The members of a class come in two distinct types: class, or static, members are associated with the class itself, while instance members are associated with individual instances of the class (i.e., with objects) There are four types of members: Class fields Class methods Instance fields Instance methods

Class Is a template that defines attributes and methods Is written by a programmer as a part of a program Does not exist when programs execute, except in the form of one or more member objects Is static in the sense that its code cannot be altered during program execution Is named by a class name

Object Must belong to some class Exists during the time that a program executes Must be explicitly declared and constructed by the execution program Has attributes that can change in value and method that can execute during program execution( The class to which the object belongs defines these attributes and methods. )

Classfield A classfield is associated with the class in which it is defined, rather than with an instance of the class. The following line declares a class field: public static final double PI = 3.14159; The static modifier says that the field is a class field. Class fields are sometimes called static fields because of this static modifier. The final modifier says that the value of the field does not change. the public modifier says that anyone can use the field. The key point to understand about a static field is that there is only a single copy of it. This field is associated with the class itself, not with instances of the class. A class field is essentially a global variable.

Class method As with class fields, class methods are declared with the static modifier: public static double radianstodegrees(double rads) { return rads * 180 / PI; Like class fields, class methods are associated with a class, rather than with an object. When invoking a class method from code that exists outside the class, you must specify both the name of the class and the method. A class method can use any class fields and class methods of its own class (or of any other class). But it cannot use any instance fields or instance methods because class methods are not associated with an instance of the class. class method is a global method, or global function.

Instance Fields Any field declared without the static modifier is an instancefield : public double r; // The radius of the circle Instance fields are associated with instances of the class, rather than with the class itself. Thus, every Circle object we create has its own copy of the double field r. In our example, r represents the radius of a circle. Thus, each Circle object can have a radius independent of all other Circle objects. Inside a class definition, instance fields are referred to by name alone. In code outside the class, the name of an instance method must be prepended by a reference to the object that contains it. For example, if we have a Circle object named c, we can refer to its instance field r as c.r Circle c = new Circle(); // Create a new Circle object; store it in variable c c.r = 2.0; // Assign a value to its instance field r, Circle d = new Circle(); // Create a different Circle object d.r = c.r * 2; // Make this one twice as big

Instance Methods Any method not declared with the static keyword is an instance method. An instancemethod operates on an instance of a class (an object) instead of operating on the class itself. To use an instance method from outside the class in which it is defined, we must prepend a reference to the instance that is to be operated on. For example: Circle c = new Circle(); // Create a Circle object; store in variable c c.r = 2.0; // Set an instance field of the object double a = c.area(); // Invoke an instance method of the object

Declaring Variables There are several kinds of variables: Member variables in a class these are called fields. Variables in a method or block of code these are called local variables. Variables in method declarations these are called parameters. Field declarations are composed of three components, in order: Zero or more modifiers, such as public or private. The field's type. The field's name.

public class Bicycle { Example private int cadence; private int gear; private int speed; public Bicycle(int startcadence, int startspeed, int startgear) { gear = startgear; cadence = startcadence; speed = startspeed; public int getcadence() { return cadence; public void setcadence(int newvalue) { cadence = newvalue; public int getgear() { return gear; public void setgear(int newvalue) { gear = newvalue; public int getspeed() { return speed; public void applybrake(int decrement) { speed -= decrement; public void speedup(int increment) { speed += increment;

Methods More generally, method declarations have six components, in order: Modifiers such as public, private,... The return type the data type of the value returned by the method, or void if the method does not return a value. The method name the rules for field names apply to method names as well, but the convention is a little different. The parameter list in parenthesis a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. An exception list The method body, enclosed between braces the method's code, including the declaration of local variables, goes here.

Overloading Methods The Java programming language supports overloading methods. public class DataArtist {... public void draw(string s) {... public void draw(int i) {... public void draw(double f) {... public void draw(int i, double f) {...

Constructors A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations except that they use the name of the class and have no return type. For example, Bicycle has one constructor: public Bicycle(int startcadence, int startspeed, int startgear) { gear = startgear; cadence = startcadence; speed = startspeed; To create a new Bicycle object called mybike, a constructor is called by the new operator: Bicycle mybike = new Bicycle(30, 0, 8) //new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields Although Bicycle only has one constructor, it could have others, including a no-argument constructor: public Bicycle() { gear = 1; cadence = 10; speed = 0; Bicycle yourbike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourbike.

Creating Objects Creating objects has three parts: Declaration: is variable declarations that associate a variable name with an object type. Instantiation: The new keyword is a Java operator that creates the object. The new operator instantiates a class by allocating memory for a new object and returning a reference to the object it created. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

Parameters You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computepayment method, and reference data types, such as objects and arrays. public Polygon polygonfrom(point[] corners) { // method body goes here public double computepayment(double loanamt, double rate, double futurevalue, int numperiods) { double interest = rate / 100.0; double partial1 = Math.pow((1 + interest), -numperiods); double denominator = (1 - partial1) / interest; double answer = (-loanamt / denominator)- ((futurevalue * partial1) / denominator); return answer;

Class level access modifiers Only two access modifiers is allowed, public and no modifier If a class is public, then it CAN be accessed from ANYWHERE. If a class has no modifer, then it CAN ONLY be accessed from same package.

Controlling Access to Members of a Class Access level modifiers determine whether other classes can use a particular field or invoke a particular method. At the member level public, private, protected, or package-private (no explicit modifier). Modifier Class Package Subclass World Public Y Y Y Y Protected Y Y Y N No modifier Y Y N N Private Y N N N

Thanks for your attension!