Variables and Java vs C++

Similar documents
Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

Java Identifiers, Data Types & Variables

CS 231 Data Structures and Algorithms, Fall 2016

Contents. 8-1 Copyright (c) N. Afshartous

Programming Language Concepts Scoping. Janyl Jumadinova January 31, 2017

Lec 7. for loops and methods

Selected Questions from by Nageshwara Rao

Chapter 3:: Names, Scopes, and Bindings

Array. Prepared By - Rifat Shahriyar

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

About this exam review

Assumptions. History

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

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

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Introduction to Programming (Java) 4/12

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter 5 Names, Bindings, Type Checking, and Scopes

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

You must declare all variables before they can be used. Following is the basic form of a variable declaration:

CS 231 Data Structures and Algorithms Fall 2018

Reminder the scope of a variable is the part of the program where that variable is visible Will this compile?

Arrays Classes & Methods, Inheritance

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

G52PGP. Lecture oo3 Java (A real object oriented language)

Following is the general form of a typical decision making structure found in most of the programming languages:

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

Understand Computer Storage and Data Types

C11: Garbage Collection and Constructors

CS121/IS223. Object Reference Variables. Dr Olly Gotel

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

Chapter 2. Procedural Programming

Chapter 6 Introduction to Defining Classes

One Ring to rule them all, One Ring to bring them all,

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

CS 211: Methods, Memory, Equality

Object Reference and Memory Allocation. Questions:

C10: Garbage Collection and Constructors

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

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

Lesson 36: for() Loops (W11D1)

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

Ryerson University Vers HAL6891A-05 School of Computer Science CPS109 Midterm Test Fall 05 page 1 of 6

Java Basic Programming Constructs

Java Bytecode (binary file)

Introduction to Java

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

A Foundation for Programming

9 Working with the Java Class Library

CSE 374 Programming Concepts & Tools

Expressions & Flow Control

1 Shyam sir JAVA Notes

Overview COMP Microprocessors and Embedded Systems. Lectures 18 : Pointers & Arrays in C/ Assembly

Chapter 1 Getting Started

CS106A, Stanford Handout #18. Writing a Class

In Java we have the keyword null, which is the value of an uninitialized reference type

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Controls Structure for Repetition

Memory and C++ Pointers

CS 61C: Great Ideas in Computer Architecture Introduction to C

Java Memory Management

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

6.092: Java for 6.170

Review: Array Initializer Lists

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

CS S-08 Arrays and Midterm Review 1

University of Palestine. Mid Exam Total Grade: 100

Operational Semantics of Cool

Getting started with Java

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Announcements. My office hours are today in Gates 160 from 1PM-3PM. Programming Project 3 checkpoint due tomorrow night at 11:59PM.

Nested Loops. A loop can be nested inside another loop.

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace

JAVA An overview for C++ programmers

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Short Notes of CS201

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Time : 1 Hour Max Marks : 30

Introduce C# as Object Oriented programming language. Explain, tokens,

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

CS201 - Introduction to Programming Glossary By

Handout 4 Conditionals. Boolean Expressions.

Introduction to Programming Using Java (98-388)

Pace University. Fundamental Concepts of CS121 1

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Object Oriented Modeling

Programmiersprachen (Programming Languages)

CS201 Some Important Definitions

Tasks for fmri-setting (Tasks of first and second pilot study at the end)

The Java programming environment. The Java programming environment. Java: A tiny intro. Java features

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Transcription:

Variables and Java vs C++ 1

What can be improved? (variables) public void godirection(string directionname) { boolean wenttoroom = false; for (Direction direction : currentroom.getdirections()) { if (direction.getdirectionname().equalsignorecase(directionname)) { wenttoroom = true; currentroom = direction.getdestinationroom(); break; if (!wenttoroom) { System.out.println("I can't go " + directionname); A) Eliminating temporary variable B) Eliminating intermediate results C) Eliminating control flow variable D) Shrinking scope of variable E) Prefer write once variable 2

What can be improved? (variables) public static void main(string[] args) { String currroomname = ""; Boolean continueplaying = true; // deals with args... Layout maplayout = UserInterface.LoadMap(newMapUrl); Map<String, Room> playmap = GameState.GenerateVirtualMap(mapLayout); Room currroom = playmap.get(maplayout.getstartingroom()); while (continueplaying) { currroomname = GameState.play(currRoom); currroom = playmap.get(currroomname); if (currroomname.equals("exit")) { continueplaying = false; A) Eliminating temporary variable B) Eliminating intermediate results C) Eliminating control flow variable D) Shrinking scope of variable E) Prefer write once variable 3

What can be improved? (variables) public static void checkfloorplan() throws Exception { //... (removed stuff) for (Room currroom : roomcollection.values()) { boolean roomfound = false; for (Direction currdirection : currroom.getdirections()) { roomfound = roomfound findroominconnecting(currroom.getname(), roomcollection.get(currdirection.getroom())); if (!roomfound) { throw new BadFloorPlanJsonException("Rooms not connected."); A) Eliminating temporary variable B) Eliminating intermediate results C) Eliminating control flow variable D) Shrinking scope of variable E) Prefer write once variable 4

What can be improved? String description; String currentroom = layout.getstartingroom(); for (int i = 0; i < layout.getrooms().length; ) { A) Eliminating temporary variable B) Eliminating intermediate results C) Eliminating control flow variable D) Shrinking scope of variable E) Prefer write once variable int currentroomindex = layout.getroomfromname(currentroom); description = layout.getrooms()[currentroomindex].getdescription(); System.out.println(description); ArrayList<String> directionname = new ArrayList<String>(); for (int j = 0; j < layout.getrooms()[currentroomindex].getdirections().length; j++) { directionname.add(layout.getrooms()[currentroomindex].getdirections()[j].getdirectionname().tolowercase()); String direction = getdirectionsoption(directionname) // More loop body 5

Which is better? A String originaldirectionname = input.substring(3); return "I can't go " + originaldirectionname + "\n"; B return "I can't go " + input.substring(3) + "\n"; 6

Which is better? A String input = scanner.nextline(); String output = gamecontroller.handleinput(input); B String output = gamecontroller.handleinput(scanner.nextline()); 7

Java and C++ Similar in: Syntax: Java was designed to use syntax similar to C++ to ease adoption Structurally: Both are object-oriented languages Different in goals: Java designed for: safety and portability C++ designed for: Control and performance 8

Java vs C++ Memory Java Automatic Allocated on stack Lifetime from function Garbage Collected All arrays All Classes Allocated on the heap Lifetime as long as referenced C++ Automatic Allocated on stack Lifetime from function Heap Allocated on the heap Lifetime managed by various methods 9

Java vs C++ Functions Java All functions belong to a class (methods) All arguments call by value static used to allow methods to be called without an object. C++ Functions just exist Classes can have functions just like in Java called methods they then get a implicit this argument 10

Java Array vs C++ Array Java Allocated on heap Checks bounds Think of as an object Size set when created Knows length C++ Allocated either on heap or stack No bounds check on accesses Think of as a pointer Size set when allocated 11

Java Array vs C++ Vector Java Array Allocated on heap Checks bounds Think of as an object Size set when created Knows length C++ std::vector Allocated on heap Can check bounds Can extend Knows length 12

13

Scrabble 14

Scrabble word score Sum of the letter values 15

Scrabble word score, continued public static int wordscore(string word) { int score = 0; for (int i = 0 ; i < word.length() ; i++) { char letter = word.charat(i); score += letterscore(letter); return score; 16

Control-flow based public static int letterscore(char c) { char upperc = Character.toUpperCase(c); switch (upperc) { case 'A': case 'E': case 'I': case 'L': case 'N': case 'O': case 'R': case 'S': case 'T': case 'U': case 'D': case 'G': case 'B': case 'C': case 'M': case 'P': return 1; return 2; return 3; case 'H': case 'V': case 'W': case 'Y': case 'K': case 'J': case 'X': case 'Q': case 'Z': default: case 'F': return 4; return 5; return 8; return 10; // handle error // should never reach here return 0; 17

Table-based Solution private static final int [] scoresbychar = {/* A */ 1, /* B */ 3, /* C */ 3, /* D */ 2, /* E */ 1, /* F */ 4, /* G */ 2, /* H */ 4, /* I */ 1, /* J */ 8, /* K */ 5, /* L */ 1, /* M */ 3, /* N */ 1, /* O */ 1, /* P */ 3, /* Q */ 10, /* R */ 1, /* S */ 1, /* T */ 1, /* U */ 1, /* V */ 4, /* W */ 4, /* X */ 8, /* Y */ 4, /* Z */ 10; public static int letterscore2(char c) { char casuppercase = Character.toUpperCase(c); int index = casuppercase - 'A'; if (index < 0 index >= 26) { // handle error return scoresbychar[index]; 18