CT 229 Fundamentals of Java Syntax

Similar documents
CT 229. CT229 Lecture Notes. Labs. Tutorials. Lecture Notes. Programming II CT229. Objectives for CT229. IT Department NUI Galway

CT 229 Arrays Continued

Getting started with Java

CST141 Thinking in Objects Page 1

Full file at

Chapter 2: Using Data

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Software and Programming 1

Chapter 2: Java Fundamentals

8/23/2014. Chapter Topics. Chapter Topics (2) Parts of a Java Program. Parts of a Java Program. Analyzing The Example. Chapter 2: Java Fundamentals

Chapter 02: Using Data

Full file at

Lesson 3: Accepting User Input and Using Different Methods for Output

Chapter 2: Using Data

CS11 Java. Fall Lecture 1

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

CS 231 Data Structures and Algorithms, Fall 2016

CT 229 Java Syntax Continued

Lec 3. Compilers, Debugging, Hello World, and Variables

CS 11 java track: lecture 1

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Course PJL. Arithmetic Operations

Software and Programming 1

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

What methods does the String class provide for ignoring case sensitive situations?

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Oct. 3 fixup - Here are notes and codes in the proper order that they should be.

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

Data Types Reference Types

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

More about JOptionPane Dialog Boxes

Introduction to Java. Nihar Ranjan Roy.

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Array. Prepared By - Rifat Shahriyar

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

ECE 122 Engineering Problem Solving with Java

CS 106 Introduction to Computer Science I

PROGRAMMING FUNDAMENTALS

Chapter 2 ELEMENTARY PROGRAMMING

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Introduction to Programming Using Java (98-388)

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

Fall 2017 CISC124 9/16/2017

COMP 110 Introduction to Programming. What did we discuss?

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

3. Java - Language Constructs I

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Course Outline. Introduction to java

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Basics of Java Programming

BCIS 3630 Dr. GUYNES SPRING 2018 TUESDAY SECTION [JAN version] GRADER COURSE WEBSITE

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

CS 251 Intermediate Programming Java Basics

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

1 Shyam sir JAVA Notes

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Exercise: Inventing Language

Object-Oriented Programming

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

BRANCHING if-else statements

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

4 Programming Fundamentals. Introduction to Programming 1 1

Lecture 2 Tao Wang 1

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Coding Standards for Java

Java Bytecode (binary file)

The price of gold. source: nowiknow.com. moodle.yorku.ca CSE 1020

Java Classes: Math, Integer A C S L E C T U R E 8

Programming. Syntax and Semantics

Program Fundamentals

Objectives. In this chapter, you will:

Introduction to Classes and Objects

Full file at

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

19. GUI Basics. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

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

Chapter 2 Primitive Data Types and Operations. Objectives

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

CS 1302 Chapter 9 (Review) Object & Classes

CHAPTER 2 Java Fundamentals

Chapter 2 Primitive Data Types and Operations

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Programming with Java

MODULE 02: BASIC COMPUTATION IN JAVA

CSc Introduction to Computing

Date: Dr. Essam Halim

JAVA WRAPPER CLASSES

Transcription:

CT 229 Fundamentals of Java Syntax 19/09/2006 CT229

New Lab Assignment Monday 18 th Sept -> New Lab Assignment on CT 229 Website Two Weeks for Completion Due Date is Oct 1 st Assignment Submission is online @ http://ecrg-vlab01.it.nuigalway.ie/uploader/submissions.html There is a link to the submission page from the main course webpage @ http://www.nuigalway.ie/staff/ted_scully/ct229/ 19/09/2006 CT229 1

Assignment Upload 19/09/2006 CT229 2

Assignments Submission Submit one file at a time You can only submit.java files Assignment Marking There will be four sections to assignment 20% for successful completion of each section No marks will be awarded unless section is running correctly 20% goes for correct programming style (naming conventions, commenting, formatting etc) Always keep a copy of your completed assignment Original Work Only!!! 19/09/2006 CT229 3

Java Style Guide Adhering to a programming style guide results in writing correct, high quality, maintainable and easily readable java code. The Java Programming Style guide can be divided into: Naming Conventions Commenting Formatting 19/09/2006 CT229 4

Naming Conventions Variable Names Variable should have mixed-case letters, beginning with lower-case use accountbalance instead of AccountBalance or accountbalance Avoid using abbreviations (accbal) or very long names Use a name that describes the function of the variable Constant Names Use all upper case letters, separating words with underscore INTEREST_RATE instead of interestrate Avoid the use of magic number, that is actual numbers that appear in the code without any explanation interestdue = 2000*10 interestdue = accountbalance * INTEREST_RATE 19/09/2006 CT229 5

Naming Conventions Methods As with variables use mixed-case letters for naming methods Method name should indicate its purpose Generally methods that return a the value of a variable have a prefix get (Example: getaccountbalance) While methods that set a variable value have a prefix set (Example: setaccountbalance) Parameter Names Follow same naming convention as used with variables 19/09/2006 CT229 6

Commenting Comments should be used to improve the readability of the program Two Types of Comments: Header Comment Single-line Comments 19/09/2006 CT229 7

Header Comment A header comment appears at the beginning of a.java file. Informs the reader of the function of the program Identifies the original author Example /* Simple Java program that prints a Hello message */ /* John Doe, Student Number: 00003112 */ NOTE!! For each assignment ensure that your name and student number is written in the header comments 19/09/2006 CT229 8

Single Line Comment Normally provides an overview of a line or a number of lines. Begin with // or nested between /* */ Do not insert useless comments Example // Get hourly pay rate in string form: convert to double ratestr = JOptionPane.showInputDialog("Enter Hourly Rate:"); rate = Double.parseDouble(rateStr); 19/09/2006 CT229 9

Formatting Formatting relates to the appearance of your code Code should be tidy and easy to read Two important types of formatting generally applied Indentation Space 19/09/2006 CT229 10

Indentation Use of indentation makes code easier to read Simple Rules for indentation After each { move the subsequent code in by three spaces Open and close parentheses { } should be inline with each other Example /* Simple Java program that prints a Hello message */ /* Ted Scully, Sept 2006 */ public class Hello { public static void main(string[] args) { System.out.println("Hello World!"); } } 19/09/2006 CT229 11

Space Use of white space improves the readability of programs 19/09/2006 CT229 12

Second Java Program Program to Calculate Employee s Total Week s Wages: 1.Look up the employee s pay rate (rate) 2.Determine the number of hours worked (hrs) in week 3.If no. of hours worked < or = 40 then regular wages (wage) = hrs*rate and overtime pay (over) = 0 4.If hrs > 40 then wage = 40*Rate and overtime pay (over) = hrs - 40) * (1.5 * rate) 5.Total Wages (total) = wage + over 19/09/2006 CT229 13

Wages.java /* Basic Java Program that asks the user for the hourly payrate and the number * of hours worked. It then calculates the total wage earned for the user */ /* Ted Scully, Sept 2006 */ import javax.swing.joptionpane; // Dialog box methods public class Wages { public static void main(string[] args) { double rate, hrs, over, wage, total; String ratestr, hoursstr; REMEMBER: For Assignments include name and student number // Get hourly pay rate in string form: convert to double ratestr = JOptionPane.showInputDialog("Enter Hourly Rate:"); rate = Double.parseDouble(rateStr); // Get hourly pay rate in string form: convert to double hoursstr = JOptionPane.showInputDialog("Enter Hours Worked:"); hrs = Double.parseDouble(hoursStr); 19/09/2006 CT229 14

Wages.java if (hrs <= 40) { wage = rate * hrs; over = 0; } else { wage = rate * 40; over = (hrs - 40) * 1.5 * rate; } total = wage + over; // Display total wage earned JOptionPane.showMessageDialog(null, "Total weekly wages are " + total); } } // Terminate program System.exit(0); 19/09/2006 CT229 15

Main Features import javax.swing.joptionpane; Loads classes from Java API that program will use javax.swing is a graphical user interface package JOptionPane is a class in package for displaying msg boxes double rate, hrs, over, wage, total; String ratestr, hoursstr; Declares existence of four variables that can hold numerical data ( double-precision floating-point ), and two variables that can hold string (i.e. text) data ratestr = JOptionPane.showInputDialog("Enter Hourly Rate:"); Invokes a method called showinputdialog, which is part of the JOptionPane class (defined javax.swing package) Displays input box with text Enter Hourly Rate ratestr is set to whatever text the user types in 19/09/2006 CT229 16

Main Features rate = Double.parseDouble(rateStr); parsedouble is a method in Double class, that converts text ( 123 ) to a double number (123.0) Double is a class defined in the Java language package (java.lang); imported automatically if (hrs <= 40) Code to make a decision: which lines will be executed next depends on the data in the variable called hrs Exactly like C total = wage + over; Sets total equal to the sum of wage and over This line is after the if-block; it is executed after whichever of the previous blocks of code is executed 19/09/2006 CT229 17

Main Features JOptionPane.showMessageDialog (null, "Total weekly wages are " + total); Method that displays a message box Two arguments: 1: usually null 2: the text to display The + joins text; automatically converts numbers to text command (statement) can be split over more than one line The ; indicates the end of a statement System.exit(0); Method of the System class: terminates the program Required for graphical programs Like Double, System is part of java.lang package, which is imported automatically at the start of the program 19/09/2006 CT229 18

Comparing C and Java Syntax Java copies basics of C syntax Expressions end in ; Almost all operators the same (Java has a few extra) Basic data types similar but not identical Same comment forms, but Java also has Javadoc comments Same decision and loop syntax, similar use of { } Java method parameters, structure and return values similar to C functions (some differences) 19/09/2006 CT229 19

Comparing C and Java Syntax Java is Object-Oriented C has nothing like Java classes (but C++ has) Basic structure of programs different main method has different syntax Class name must be the same as the.java file name Classes and methods in Java standard API completely different from C Standard Library functions Java has automatic garbage collection: no malloc(), no free(), no pointers! 19/09/2006 CT229 20

Primitive Data Types All variables must be declared with a name and a data type before they can be used May declare multiple variables of same type: int a, b, c, d; Can have declarations in middle of executable code Primitive Data Types: Primitive Data Types are similar to variables in C. However, they are defined more precisely in the interests of portability. int integer (whole number, pos or neg; 32 bits) long integer (can hold larger value than int; 64 bits) short integer (can hold 16-bit integers) byte integer (can hold 8-bit integers) float real number (with decimal point; 32 bits) double real number (larger precision/size; 64 bits) char holds a single character (Unicode, 16 bits) boolean can be either true or false 19/09/2006 CT229 21

Primitive Data Types Unlike C, primitive data types all have fixed storage size Example boolean result = true; char capitalc = 'C'; byte b = 100; short s = 10000; int i = 100000; 19/09/2006 CT229 22

String Data Type String Class defined in java.lang (imported automatically) Stores text (multiple characters) Example public class Main { public static void main(string[] args) { String firstname = John "; String lastname = Doe"; String fullname = firstname + lastname; System.out.print(fullName); } } 19/09/2006 CT229 23

Wrapping Primitive Data Types in a Class For every primitive data type, there is a type-wrapper class While primitive types have no associated methods, their associated wrapper classes do Example int number = 5; // Integer is the wrapper class for the primitive type int Integer numberwrapper = new Integer(number); double realnumber1 = number1wrapper.doublevalue(); System.out.println(realNumber1); 19/09/2006 CT229 24

Constants The value of a variable can be changed, but the value of a constant is fixed To create a named constant in Java you use the final type modifier A field declared final cannot be changed in the program Remember in C: #define STUDENT_NUMBER 00112233 Example final int STUDENT_NUMBER = 00112233; final String HELLO_MESSAGE = "Welcome to the Class CT229"; System.out.println(STUDENT_NUMBER); System.out.println(HELLO_MESSAGE); 38043 Welcome to the Class CT229 19/09/2006 CT229 25

Scope of Variables Class Variables: Declared as part of the class definition Have a class-wide scope (visibility, life-span) Can be accessed by member methods of class Local variables: Variables declared within a method Visible only in this method Two or more methods can use same names for local variables public class variable: Visible throughout the program Will cover public/private visibility modifiers later 19/09/2006 CT229 26

Scope of Variables 19/09/2006 CT229 27

Primitive Type Conversion Converting from one type to another is possible in a number of ways in Java. One solution is to use wrapper classes Example int number1 = 5; // Integer is the wrapper class for the primitive type int Integer number1wrapper = new Integer(number1); // Converts int number to double double realnumber1 = number1wrapper.doublevalue(); System.out.println("double value is "+realnumber1); 19/09/2006 CT229 28

Type Conversion NOTE! Cannot do assignments that involve potential loss of data: OK to assign int value to double variable (implicit cast) Error to assign double value to float variable Could also use casting to force conversion between numeric types Example float floatnumber; double doublenumber = 1.234; floatnumber = (float)doublenumber; 19/09/2006 CT229 29

Type Conversion Convert using methods of number classes Can convert a String to a primitive data type int num = Integer.parseInt(str); double rate = Double.parseDouble(rateStr); Can convert a primitive data type to a String String str = Integer.toString(num); Using this method you cannot convert directly from one primitive data type to another 19/09/2006 CT229 30