EXERCISES SOFTWARE DEVELOPMENT I. 04 Arrays & Methods 2018W
|
|
- Margaret Charles
- 5 years ago
- Views:
Transcription
1 EXERCISES SOFTWARE DEVELOPMENT I 04 Arrays & Methods 2018W
2 Solution First Test
3 DATA TYPES, BRANCHING AND LOOPS Complete the following program, which calculates the price for a car rental. First, the program reads the user's driving license number ("Führerscheinnummer") and the desired number of days for the rental, until the input is valid. The company has currently a special offer: If a car is rented for full weeks (i.e. exactly 7, 14, 21,.. days), one day per week is for free. Consider the following: The price per day is The number of days for a car rental must be greater than 0. Make sure that the license number follows the format 2018xxx, where xxx stands for three arbitrary numbers. Valid examples are therefore , or , while or are invalid. Use Input.readInt() to read in an integer value. TODO Software Development I // 2018W // 3
4 DATA TYPES, BRANCHING AND LOOPS Complete the following program, which calculates the price for a car rental. First, the program reads the user's driving license number ("Führerscheinnummer") and the desired number of days for the rental, until the input is valid. The company has currently a special offer: If a car is rented for full weeks (i.e. exactly 7, 14, 21,.. days), one day per week is for free. Consider the following: The price per day is The number of days for a car rental must be greater than 0. Make sure that the license number follows the format 2018xxx, where xxx stands for three arbitrary numbers. Valid examples are therefore , or , while or are invalid. Use Input.readInt() to read in an integer value. Software Development I // 2018W // 4
5 Arrays in Java (Part I)
6 ARRAYS :: DATA STRUCTURE Problem: So far only primitive variables (int age, float value, etc.) Data structures for large number of elements Example: Hotel Venetian in Las Vegas has 7128 rooms; Reservation system which room is available? boolean availroom1, availroom2,..., availroom7128; Feasible structures for associated data needed Example: date ( : day, month, year) int day, month, year - this declaration does not allow to infer the relation between these variables In the given notation, a second date would be declared as int day2, month2, year2 - not very intuitive to read or use Better: The entire date should form a coherent unit 'Date' should be usable as a single parameter like a primitive variable Solution: Arrays An array is a container object that holds a fixed number of values of a single type date-array, availroomsarray, etc. Software Development I // 2018W // 6
7 I ARRAYS :: CREATING, INITIALIZING, AND ACCESSING Each item in an array is called an element, and each element is accessed by its numerical index The length of an array is established when the array is created; i.e., after creation its length is fixed Example: Declare date as array of three integer values int[] date = new int[3]; // indices from 0 to 2 date[0] = 14; date[1] = 11; assigning values date[2] = 2018; Example 2: Second date array int[] date2 = new int[3]; // a second date Explicit allocation with new operator The array is of type int[] Software Development I // 2018W // 7
8 ARRAYS :: GENERAL INFORMATION An array has a fixed: Name Type Length Array sizes cannot be changed during the execution of the code Array variables do not contain the array itself, but a reference to a space in the main memory date date has room for three elements (day, month, year) Elements have same data type! The elements are accessed by their index (0 2) In Java, array indices start at 0 (last element = length 1) Length can be determined via date.length Software Development I // 2018W // 8
9 ARRAYS :: CREATING, INITIALIZING, AND ACCESSING Declaration and initialization can be done separately int[] date; // data array with 3 elements (e.g., day, month, year) date = new int[3]; // not fixed; can be redeclared to store 6 elements, // e.g., day, month, year, hour, minute, second date = new int[6]; // 'old' date array: garbage collector! Initialization can be also done at declaration time int[] date = { 14, 11, 2018 ; // length implicit, fixed int[] daysofmonth = {31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30, 31 Software Development I // 2018W // 9
10 ARRAYS :: CREATING, INITIALIZING, AND ACCESSING Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. Example: Declaration and allocation of an integer array int[] numbers; numbers = new int[100]; Interpretation Each array has: - name - type - length The new operator allocates memory to hold 100 integer values (100 x 32 bits = 100 x 4 bytes = 400 bytes) In Java the new operator initializes all the array elements automatically numeric data types: 0 or 0.0 boolean type: false character types: '\0' reference types: null Software Development I // 2018W // 10
11 ARRAYS :: CREATING, INITIALIZING, AND ACCESSING Additional examples Declaration only float[] annualrain; char[] text; int[] studnumbers; // A float array // A char array // An int array Declaration + allocation // allocate space for 90 floats float[] annualrain = new float[90]; // allocate space for characters char[] text = new char[10000]; // allocate space for 100 integers int[] studnumbers = new int[100]; Software Development I // 2018W // 11
12 ARRAYS :: OPERATING WITH INDICES Declare and initialize an integer array of length 12 which stores the number of days for each month: int[] daysofmonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31; What about the following statement? daysofmonth[m % 12]; // m-1...current month // (m-1)+1 = m...next month Results in number of days of the next month How many days does a month 'm' have? (1 <= m <= 12) daysofmonth[m - 1]; // [0]...[11] Software Development I // 2018W // 12
13 ARRAYS :: OPERATING WITH INDICES Declare and initialize an integer array of length 12 which stores the number of days for each month: int[] daysofmonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31; Array indices does not have to be a fixed integer value; it can be an arbitrary complex expression, e.g., a[i*3/2+3] = j; Software Development I // 2018W // 13
14 ARRAYS :: INDEXING PROBLEMS (DIN ) == November 14, 2018 (US) == (ISO 8601) Assignment of month November (11) to the date array date[1] = 11; Which date format, i.e., Day? Month? Year? One has to remember which index stores which value Possible solution: Use constants to refer to indices static final int DAY_INDEX = 0; // or DAY static final int MONTH_INDEX = 1; // or MONTH static final int YEAR_INDEX = 2; // or YEAR Utilization date[day_index] = 14; date[month_index] = 11; date[year_index] = 2018; Software Development I // 2018W // 14
15 ARRAYS :: GENERAL INFORMATION 'Array' is the first complex (i.e., reference ) data type A variable of primitive data type (int, char, float, etc.) contains its value Array variables do not contain (store) the array itself but reference a space in the main memory (RAM) that was allocated explicitly using the new operator Example: int[] array = new int[10]; or implicitely Example: int[] date = { 14, 11, 2014 ; Consequence: Its not possible to compare arrays (as you compare primitive vars.) if(array1 == array2) {... An array is a list with a fixed size and it contains 1 or more elements of same data type Does not compare array elements but address reference Software Development I // 2018W // 15
16 ARRAYS :: MEMORY ORGANIZATION int[] daysofmonth = new int[12]; Memory addresses daysofmonth array[3] array[7] array[11] Address of the first element of the array in memory array[0] array[1] array[2] array[4] array[5] array[6] array[8] array[10] array[9] Software Development I // 2018W // 16
17 ARRAYS :: MEMORY ORGANIZATION int[] daysofmonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31; Memory addresses daysofmonth array[3] array[7] array[11] Address of the first element of the array in memory array[0] array[1] array[2] array[4] array[5] array[6] array[8] array[10] array[9] Software Development I // 2018W // 17
18 ARRAYS :: EXAMPLE Given: A float[] storing X values to describe the rainfall in the last X years Calculate the total and average rainfall over the entire time // Declare and fill the array with the appropriate data float[] annualrain = getannualrain(); float total = 0.0f; for (int year = 0; year < annualrain.length; year++) { // Each array element is a "float" total = total + annualrain[year]; // for year System.out.println("Total: " + total); System.out.println("Average: " + total / annualrain.length); Software Development I // 2018W // 18
19 ARRAYS :: EXAMPLE Given: A float[] storing X values to describe the rainfall in the last X years Calculate the total and average rainfall over the entire time // Declare and fill the array with the appropriate data float[] annualrain = getannualrain(); float total = 0.0f; for (int year = 0; year < annualrain.length; year++) { // Each array element is a "float" total = total + annualrain[year]; // for year System.out.println("Total: " + total); System.out.println("Average: " + total / annualrain.length); Software Development I // 2018W // 19
20 ARRAYS :: BOUNDS Remember: Indices range from 0 to length 1 public class ArrayBounds { public static void main(string[] args) { int[] array; // declaration array = new int[10]; // creation for (int i = 1; i < array.length + 1; i++) { array[i] = i * 2; System.out.println(array[i]); Software Development I // 2018W // 20
21 Methods for Structual Programming Spaghetti code is a pejorative phrase for source code that has a complex and tangled control structure,. It is named such because program flow is conceptually like a bowl of spaghetti, i.e. twisted and tangled.
22 I METHODS :: OVERVIEW Collection of statements that are grouped together to perform a certain operation Examples System.out.println() Input.readInt() Purpose of Methods Reuse code that is frequently used Structuring program code, high level of readability Methods are testable units Verified Units must not be considered in Debugging Divide & Conquer Approach Complex Problems are just a combinations of simple problems Complex Problems are split into sub problems until we can solve them Public static void main(string[] arg) { method(); static void method() { Software Development I // 2018W // 22
23 I METHODS :: DEFINITION public static int sum(int a, int b) { // method body return a+b; Method declarations have several components Modifiers such as private, public, static etc. Return Type the data type of the value returned by the method, or void Method Name Parameter List A comma-seperated list of input parameters, preceded by their data types, enclosed in parentheses (), or empty parentheses if no parameters Method Body The code, enclosed between braces Naming a method By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase readint(), print(), isempty(),.. Software Development I // 2018W // 23
24 METHODS :: DEFINITION public static int sum(int a, int b) { // method body return a+b; Calling a method When method is called, program control gets transferred to the called method This called method returns control to the caller in two conditions, Return statement is executed It reaches the method ending brace Examples System.out.println( This method does not have any return value ); int result = sum(5,5); Software Development I // 2018W // 24
25 METHODS :: DEFINITION public static void printsum(int a, int b) { // method body System.out.println(a+b); Calling a method When method is called, program control gets transferred to the called method This called method returns control to the caller in two conditions, Return statement is executed It reaches the method ending brace Examples System.out.println( This method does not have any return value ); int result = sum(5,5); printsum(5,5); Software Development I // 2018W // 25
26 METHODS :: STRUCTURING PROGRAM CODE Sum() sum = 0 read( number) while number > 0 sum = sum + number read( number) write( sum) public class Sum { public static void main(string[] args) { int sum = 0; int number; System.out.print("Please enter number (<=0 for exit): "); number = Input.readInt(); while (number > 0) { sum = sum + number; System.out.print("Please enter number (<=0 for exit): "); number = Input.readInt(); System.out.print("Sum of numbers: "); System.out.println(sum); Repeated Code! Software Development I // 2018W // 26
27 METHODS :: STRUCTURING PROGRAM CODE Sum() sum = 0 read( number) while number > 0 sum = sum + number read( number) public class Sum { public static void main(string[] args) { int sum = 0; int number; number = enternumber(); while (number > 0) { sum = sum + number; number = enternumber(); System.out.print("Sum of numbers: "); System.out.println(sum); public static int enternumber() { write( sum) Software Development I // 2018W // 27 int number; System.out.print("Please enter number (<=0 for exit): "); number = Input.readInt(); return number; Repeated code is now extracted as method
28 I METHODS :: JAVA SPECIFICATION EXTRACT public static int readint() { {MethodModifier MethodHeader Methodbody Result Identifier ( [FormalParameterList] ) int readint () Attention: If result is not void your method body has to have a return statement. Java Language Specification (Version 8 Page 228) Software Development I // 2018W // 28
29 I METHODS :: RETURN VALUE public class Input { Result is of Type int // Numbers returned will be within [ , ]. public static int readint() { int n = 0; boolean valid = false; do { try { n = Integer.parseInt(nextLine()); valid = true; catch (NumberFormatException e) { System.out.print("Not a valid int, please try again: "); while (!valid); return n; Return value is of Type int Software Development I // 2018W // 29
30 I METHODS :: RE-STRUCTURING CODE Sum() sum = 0 number=0 read( number) sum = sum + number while number > 0 write( sum) public class Sum { public static void main(string[] args) { // Init int number = 0; int sum = 0; // Read In do { System.out.println("Enter positive number or 0 to quit: "); number = Input.readInt(); sum += number; while (number > 0); // Output printsum(sum); Attention: Program works for number >= 0 but not for number < 0 Software Development I // 2018W // 30
31 I METHODS :: RE-STRUCTURING CODE Sum() sum = 0 number=0 read( number) sum = sum + number while number > 0 public class Sum { public static void main(string[] args) { // Init int number = 0; int sum = 0; // Read In do { System.out.println("Enter positive number or 0 to quit: "); number = readnumbergreaterorequalzero(); sum += number; while (number > 0); // Output printsum(sum); write( sum) Software Development I // 2018W // 31
32 I METHODS :: RE-STRUCTURING CODE Sum() sum = 0 number=0 read( number) sum = sum + number private static int readnumbergreaterorequalzero() { int n = 0; n = Input.readInt(); while (n < 0) { System.out.print("Int below zero, please try again: "); n = Input.readInt(); return n; private static void printsum(int sum) { System.out.println("Summe ist: " + sum); while number > 0 write( sum) Software Development I // 2018W // 32
33 I METHODS :: RE-STRUCTURING CODE Extract Methods Separate Method for each block Consider Return Type Return Value Formal Parameters Actual Parameters Method Modifiers public class CheckDigit { public static void main(string[] args) { int baseid = 0; do { System.out.println("Enter a BaseId with 6 digits" +" (no preceding zero): "); baseid = Input.readInt(); while (baseid < baseid > ); System.out.printf("Base ID : %d\n", baseid); Software Development I // 2018W // 33
34 METHODS :: RE-STRUCTURING CODE Extract Methods Return Type int Return Value baseid Formal Parameters None Actual Parameters None Method Modifiers private static public class CheckDigit { public static void main(string[] args) { int baseid = readbaseid(); printbaseid(baseid); private static int readbaseid() { int baseid = 0; do { System.out.println("Enter a BaseId with 6 digits" +" (no preceding zero): "); baseid = Input.readInt(); while (baseid < baseid > ); return baseid; Software Development I // 2018W // 34
35 METHODS :: RE-STRUCTURING CODE Extract Methods Return Type void Return Value None Formal Parameters int mybaseid Actual Parameters baseid Method Modifiers private static public class CheckDigit { public static void main(string[] args) { int baseid = readbaseid(); printbaseid(baseid); private static void printbaseid(int mybaseid) { System.out.printf("Base ID : %d\n", mybaseid); Software Development I // 2018W // 35
36 O FURTHER REFINEMENT :: GENERALISATION Generalize Methods Think what would change if the digit would have size 5, 7, Consider Return Type Return Value Formal Parameters Actual Parameters Method Modifiers public class CheckDigit { public static void main(string[] args) { int baseid = readbaseid(); printbaseid(baseid); private static int readbaseid() { int baseid = 0; do { System.out.println("Enter a BaseId with 6 digits" +" (no preceding zero): "); baseid = Input.readInt(); while (baseid < baseid > ); return baseid; Software Development I // 2018W // 36
37 FURTHER REFINEMENT :: GENERALISATION Generalize Methods Return Type int Return Value baseid Formal Parameters int digits, lower, upper Actual Parameters 6, , Method Modifiers private static Software Development I // 2018W // 37 public class CheckDigit { public static void main(string[] args) { int baseid = readbaseid(); printbaseid(baseid); private static int readbaseid() { return readbaseid(6, , ); private static int readbaseid(int digits, int lower, int upper) int baseid = 0; do { System.out.printf("Enter a BaseId with %d digits" baseid = Input.readInt(); +" (no preceding zero): \n", digits); while (baseid < lower baseid > upper); return baseid;
38 I FURTHER METHODS Multiple Return Values Arrays as a Return Type Manipulate Input Pass-By-Reference Software Development I // 2018W // 38 private static int[] calcsumandaverage(int[] array){ int sum=0; for (int i = 0; i < array.length; i++) { sum+=array[i]; return new int[]{sum,sum/array.length; private static void replacenegative(int[] array, int replace) { for (int i = 0; i < array.length; i++) { if (array[i] < 0) { array[i] = replace;
39 EXERCISES SOFTWARE DEVELOPMENT I 04 Arrays & Methods 2018W
Exercises Software Development I. 06 Arrays. Declaration, Initialization, Usage // Multi-dimensional Arrays. November 14, 2012
Exercises Software Development I 06 Arrays Declaration, Initialization, Usage // Multi-dimensional Arrays November 4, 202 Software Development I Winter term 202/203 Institute for Pervasive Computing Johannes
More informationCOMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette
COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.
More informationCONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays
CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202
More informationFundamentals of Programming Data Types & Methods
Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators
More informationArray Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)
Array Basics: Outline Arrays (Savitch, Chapter 7) TOPICS Array Basics Arrays in Classes and Methods Programming with Arrays Searching and Sorting Arrays Multi-Dimensional Arrays Static Variables and Constants
More informationArrays. Eng. Mohammed Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;
More informationProgram Fundamentals
Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationLast Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it
Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]
More informationChapter 6 SINGLE-DIMENSIONAL ARRAYS
Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk What is an Array? A single array variable can reference
More informationCOE318 Lecture Notes Week 4 (Sept 26, 2011)
COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details
More informationPROGRAMMING FUNDAMENTALS
PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationSelected Questions from by Nageshwara Rao
Selected Questions from http://way2java.com by Nageshwara Rao Swaminathan J Amrita University swaminathanj@am.amrita.edu November 24, 2016 Swaminathan J (Amrita University) way2java.com (Nageshwara Rao)
More informationExample: Computing prime numbers
Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationLexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a
More informationInstructor: Eng.Omar Al-Nahal
Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar
More informationMethod OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More information( &% class MyClass { }
Recall! $! "" # ' ' )' %&! ( &% class MyClass { $ Individual things that differentiate one object from another Determine the appearance, state or qualities of objects Represents any variables needed for
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationLecture Set 4: More About Methods and More About Operators
Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static
More informationLecture Set 4: More About Methods and More About Operators
Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static
More informationSAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1
FACULTY OF SCIENCE AND TECHNOLOGY SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1 ACADEMIC SESSION 2014; SEMESTER 3 PRG102D: BASIC PROGRAMMING CONCEPTS Section A Compulsory section Question
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationTHE CONCEPT OF OBJECT
THE CONCEPT OF OBJECT An object may be defined as a service center equipped with a visible part (interface) and an hidden part Operation A Operation B Operation C Service center Hidden part Visible part
More informationExpressions and Data Types CSC 121 Spring 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types
More informationBuilding Java Programs. Chapter 2: Primitive Data and Definite Loops
Building Java Programs Chapter 2: Primitive Data and Definite Loops Copyright 2008 2006 by Pearson Education 1 Lecture outline data concepts Primitive types: int, double, char (for now) Expressions: operators,
More informationBIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic
BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines
More informationSoftware and Programming 1
Software and Programming 1 Lab 1: Introduction, HelloWorld Program and use of the Debugger 17 January 2019 SP1-Lab1-2018-19.pptx Tobi Brodie (tobi@dcs.bbk.ac.uk) 1 Module Information Lectures: Afternoon
More informationAll copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva
All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..
More informationFeatures of C. Portable Procedural / Modular Structured Language Statically typed Middle level language
1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC
More informationLast Class. More on loops break continue A bit on arrays
Last Class More on loops break continue A bit on arrays public class February2{ public static void main(string[] args) { String[] allsubjects = { ReviewArray, Example + arrays, obo errors, 2darrays };
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 3
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning
More information3. Java - Language Constructs I
Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks
More informationComputer Programming, I. Laboratory Manual. Experiment #3. Selections
Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3
More informationComputational Expression
Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name
More informationGetting started with Java
Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving
More informationA very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern
School of Computer Science, University of Birmingham. Java Lecture notes. M. D. Ryan. September 2001. A very simple program Week 2: variables & expressions Variables, assignments, expressions, and types.
More information12/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.
Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.
More informationArray. Prepared By - Rifat Shahriyar
Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types
More informationArray. Array Declaration:
Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More informationTopics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)
Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationExercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014
Exercises Software Development I 05 Conversions and Promotions; Lifetime, Scope, Shadowing November 5th, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute
More information1 Lexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler
More informationAssoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down
More informationIntroduction to Java https://tinyurl.com/y7bvpa9z
Introduction to Java https://tinyurl.com/y7bvpa9z Eric Newhall - Laurence Meyers Team 2849 Alumni Java Object-Oriented Compiled Garbage-Collected WORA - Write Once, Run Anywhere IDE Integrated Development
More informationCSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School
CSE 201 JAVA PROGRAMMING I Primitive Data Type Primitive Data Type 8-bit signed Two s complement Integer -128 ~ 127 Primitive Data Type 16-bit signed Two s complement Integer -32768 ~ 32767 Primitive Data
More informationJava Bytecode (binary file)
Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.
More informationReview Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous
Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:
More informationINDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line
A SIMPLE JAVA PROGRAM Class Declaration The Main Line INDEX The Line Contains Three Keywords The Output Line COMMENTS Single Line Comment Multiline Comment Documentation Comment TYPE CASTING Implicit Type
More informationChapter 9 Introduction to Arrays. Fundamentals of Java
Chapter 9 Introduction to Arrays Objectives Write programs that handle collections of similar items. Declare array variables and instantiate array objects. Manipulate arrays with loops, including the enhanced
More informationMotivation was to facilitate development of systems software, especially OS development.
A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.
More informationJava Coding 3. Over & over again!
Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java
More informationLesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL
Lesson 06 Arrays MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Array An array is a group of variables (called elements or components) containing
More informationCS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University
CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Java basics: Compilation vs Interpretation Program structure Statements Values Variables Types Operators and Expressions
More informationCSC Java Programming, Fall Java Data Types and Control Constructs
CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference
More informationExercises Software Development I. 08 Objects II. Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014
Exercises Software Development I 08 Objects II Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014 Software Development I Winter term 2014/2015 Priv.-Doz.
More informationAgenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationHigh Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd
El-Shorouk Academy Acad. Year : 2013 / 2014 High Institute of Computer Science & Information Technology Term : 1 st Year : 2 nd Computer Science Department Object Oriented Programming Section (1) Arrays
More informationLexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler
More informationDM550 Introduction to Programming part 2. Jan Baumbach.
DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net COURSE ORGANIZATION 2 Course Elements Lectures: 10 lectures Find schedule and class rooms in online
More informationPieNum Language Reference Manual
PieNum Language Reference Manual October 2017 Hadiah Venner (hkv2001) Hana Fusman (hbf2113) Ogochukwu Nwodoh( ocn2000) Index Introduction 1. Lexical Convention 1.1. Comments 1.2. Identifiers 1.3. Keywords
More informationDefining Classes and Methods
Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.
More informationSimple Java Reference
Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...
More informationData Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.
Data Structures 1 Data structures What is a data structure? Simple answer: a collection of data equipped with some operations. Examples Lists Strings... 2 Data structures In this course, we will learn
More informationCS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University
CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More informationChapter 2: Using Data
Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that
More informationExpressions and Data Types CSC 121 Fall 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationCOMP6700/2140 Data and Types
COMP6700/2140 Data and Types Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU February 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140 Data and Types February
More informationLecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan
Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful
More informationIntroduction to Object-Oriented Programming
Introduction to Object-Oriented Programming Arrays, Part 1 of 2 Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Arrays, Part 1 of 2 1 / 14 Modeling Aggregates As you ve seen, you
More informationCS121/IS223. Object Reference Variables. Dr Olly Gotel
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223
More informationSoftware and Programming 1
Software and Programming 1 Lab 1: Introduction, HelloWorld Program and use of the Debugger 11 January 2018 SP1-Lab1-2017-18.pptx Tobi Brodie (tobi@dcs.bbk.ac.uk) 1 Module Information Lectures: Afternoon
More informationProgramming Lecture 3
Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements
More informationSOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)
SOFTWARE DEVELOPMENT 1 Control Structures 2018W (Institute of Pervasive Computing, JKU Linz) WHAT IS CONTROL FLOW? The control flow determines the order in which instructions are executed. Default: from
More informationMotivation was to facilitate development of systems software, especially OS development.
A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.
More informationBuilding Java Programs
Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 2 Data and expressions reading: 2.1 3 The computer s view Internally, computers store everything as 1 s and 0
More informationCS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output
CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables
More informationCOMP 202 Java in one week
COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationAn overview of Java, Data types and variables
An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public
More informationCS171:Introduction to Computer Science II
CS171:Introduction to Computer Science II Department of Mathematics and Computer Science Li Xiong 1/24/2012 1 Roadmap Lab session Pretest Postmortem Java Review Types, variables, assignments, expressions
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 05 / 31 / 2017 Instructor: Michael Eckmann Today s Topics Questions / Comments? recap and some more details about variables, and if / else statements do lab work
More informationJava Primer 1: Types, Classes and Operators
Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,
More informationJava Notes. 10th ICSE. Saravanan Ganesh
Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses
More informationJOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide
Module 3 Identifiers, Keywords, and Types Objectives Upon completion of this module, you should be able to: Use comments in a source program Distinguish between valid and invalid identifiers Recognize
More informationIntroduction to Java & Fundamental Data Types
Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains
More informationLecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18
Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical
More informationEx: If you use a program to record sales, you will want to remember data:
Data Variables Programs need to remember values. Ex: If you use a program to record sales, you will want to remember data: A loaf of bread was sold to Sione Latu on 14/02/19 for T$1.00. Customer Name:
More informationCSE 114 Computer Science I
CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?
More informationLesson 3: Accepting User Input and Using Different Methods for Output
Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program
More information