Docsity

Lecture Slides on Programming Basics and Your 1st Program | CS 121, Assignments of Computer Science

Toggle sidebar
bg1
1
CS121/IS223 Week 1, Slide 1
CS121:Getting Started
A) Programming Basics & Your 1st Program
B) Basic Ingredients & Sim ple Instructions
Dr Olly Gotel
http://csis.pace.e du/~ogotel
Having problems?
-- Come see me or call me in my office hours
-- Use the CSIS programming tutors
CS121/IS223 Week 1, Slide 2
Today’s Agenda (Part A)
• Syllabus / Questionnaires / H istory
• Exercise – tour guide / the role of clear instr uctions
• Groundwork:
– program s, programmers, programmi ng languages
• Traditional first program – “Hello World!”
• Getting started with Java and Eclipse
CS121/IS223 Week 1, Slide 3
Later in the Week (Part B)
• Exercise - cooking up some r ecipes and writing code
• Assembling ingredients:
– types, v alues, variables, declarations , assignment
• Doing things with ingredients :
– simple s tatements/expressions & op erators
CS121/IS223 Week 1, Slide 4
Questionnaire: Temperatures
Fahrenheit = ((9.0 / 5.0) * Ce lsius) + 32
CS121/IS223 Week 1, Slide 5
Questionnaire: Flowcharts
• Flow of logic, sequence of ins tructions, examples of
John von Neumann
Start
i = 0
Print i
i < 10
i = i + 1
Stop
Yes
No
CS121/IS223 Week 1, Slide 6
Questionnaire: Getting Dressed
• Use trees to help you think!
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a

Partial preview of the text

Download Lecture Slides on Programming Basics and Your 1st Program | CS 121 and more Assignments Computer Science in PDF only on Docsity!

CS121/IS223 Week 1, Slide 1

CS121:Getting Started

A) Programming Basics & Your 1st^ Program B) Basic Ingredients & Simple Instructions Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223 Week 1, Slide 2

Today’s Agenda (Part A)

  • Syllabus / Questionnaires / History
  • Exercise – tour guide / the role of clear instructions
  • Groundwork:
    • programs, programmers, programming languages
  • Traditional first program – “Hello World!”
  • Getting started with Java and Eclipse CS121/IS223 Week 1, Slide 3

Later in the Week (Part B)

  • Exercise - cooking up some recipes and writing code
  • Assembling ingredients:
    • types, values, variables, declarations, assignment
  • Doing things with ingredients:
    • simple statements/expressions & operators CS121/IS223 Week 1, Slide 4

Questionnaire: Temperatures

Fahrenheit = ((9.0 / 5.0) * Celsius) + 32 CS121/IS223 Week 1, Slide 5

Questionnaire: Flowcharts

  • Flow of logic, sequence of instructions, examples of John von Neumann Start i = 0 Print i i < 10 i = i + 1 Stop Yes No CS121/IS223 Week 1, Slide 6

Questionnaire: Getting Dressed

  • Use trees to help you think!

CS121/IS223 Week 1, Slide 7

Questionnaire: Getting Coffee

  • Leave until later… CS121/IS223 Week 1, Slide 8

History Time

“The History of Computers” Perhaps watch ‘ ‘Pirates of Silicon Valley’ CS121/IS223 Week 1, Slide 9

Exercise

  • Pick any landmark in New York (not Brooklyn Bridge!)
  • Write down detailed instructions for how to get to it from W200A (One Pace Plaza) - words only
  • These instructions must be suitable to give a new visitor to New York Put your name on but don’t say where you are going CS121/IS223 Week 1, Slide 10

What Have You Just Done?

  • In essence, you have just written a program!
  • You are a programmer!
  • You didn’t have to use any funny jargon! You used a form of pseudocode to express an algorithm
  • You didn’t even have to touch a computer!
  • But is it precise and unambiguous? We’ll see later… Dispelling some myths -- programming is not scary! CS121/IS223 Week 1, Slide 11

Pseudocode

  • English-like description of how a program will work
  • High-level
  • Written in general terms
  • Programming-language independent CS121/IS223 Week 1, Slide 12

Programs

  • Sequence of instructions
  • Computer program is a sequence of instructions carried out by a computer
  • Computers are really dumb machines - they are only useful when they run programs
  • If the instructions are wrong, unclear, ambiguous or missing … the computer WILL fail in its task (GIGO - garbage in, garbage out)
  • You need to be explicit & precise

CS121/IS223 Week 1, Slide 19

A Note on Binary

The machine only understands machine language, which consists of zeros and ones (current passing through or not) CS121/IS223 Week 1, Slide 20

Programming Language

  • A textual or visual language used to write a program
  • Why use a language?
  • Examples?
  • The meaning of the program has to be unambiguous & consistent
  • You have to be precise Compare with learning a “foreign” language CS121/IS223 Week 1, Slide 21

Levels of Programming Language

  • High-level language: x = y + z
  • Assembly language: LOAD A, # LOAD B, #6 ADD A, B STORE A, #
  • Machine language: 00100100 00000101 00100100 00000110 (^00001110) 00100110 00000111 01000110 00010100 (^00010010) ……………. Assembler Compiler / Interpreter With Java we do something a bit different CS121/IS223 Week 1, Slide 22

Syntax

  • Grammatical rules of a language:
    • valid words
    • valid punctuation
    • how to form sentences
  • Unlike speaking a 2nd^ language, when you write a program you have to be syntactically correct. Remember, your computer is not as smart as a human! High-level languages ONLY on this course! “Do fink yoo (this is right]!` CS121/IS223 Week 1, Slide 23

Semantics

  • A program can be syntactically correct but never do anything useful
  • The meaning of what is written in a programming language: - precise definition of every statement you use - no ambiguity or inconsistency - determinism
  • Perhaps like speaking a 2nd^ language, you have mastered the grammar & can speak eloquently, but you still speak nonsense to locals “Students hate annoying professors ” “Students hate annoying professors ” High-level languages ONLY on this course! CS121/IS223 Week 1, Slide 24

Types of Program

  • Operating systems:
    • Windows XP
    • Red Hat Linux
  • Application programs:
    • word processor
    • spreadsheet
    • games
    • web browser
  • Embedded programs:
    • what do you think is inside your cell phone or digital camera? Systems programming Application programming

CS121/IS223 Week 1, Slide 25

Types of Programming Language

  • Paradigms for thinking about problems
    • imperative languages
    • functional languages
    • object-oriented languages
    • declarative languages
    • more… We will start in imperative mode, to cover the basics, then slowly introduce OO concepts CS121/IS223 Week 1, Slide 26 - LOGO: http://el.media.mit.edu/logo-foundation/ - TRY THIS OUT!!! Create me a program to draw a house!

A Very Simple Language

Forward 50 Right 90 Forward 50 Right 90 Forward 50 Right 90 Forward 50 Right 90 For kids! CS121/IS223 Week 1, Slide 27

Another Simple Language

  • Karel the Robot:
  • http://www.cs.mtsu.edu/~untch/karel/ http://csis.pace.edu/~bergin/karel.html TurnOn(); Move(); Move(); PickBeeper(); Move(); TurnLeft(); Move(); Move(); PutBeeper(); Move(); TurnOff(); For newbies - try this out too! Check out Karel J. Robot CS121/IS223 Week 1, Slide 28

Imperative Programming

  • Operates by a sequence of commands that change the value of data elements: - typified by assignment & iteration - a kind of “procedural programming”
  • Data & commands that operate on them are kept separate
  • Primacy of commands OO programming:
    • Data & commands which access data are treated as a unit
    • Primacy of data CS121/IS223 Week 1, Slide 29

Write Code, Then What?

  • Write code in a high-level programming language
  • It is then either compiled or interpreted (i.e. translated into machine code)
  • Compilers are programming-language specific (usually) CS121/IS223 Week 1, Slide 30

If Program is Compiled

Type in program source code (use an editor or IDE) Save code to file Compile file (use compiler for language used & target platform) Run program Debug Fix syntax Fix semantics Translates to machine code “en masse”

CS121/IS223 Week 1, Slide 37

Commercial Use of Java

BIG benefit of Java = portability CS121/IS223 Week 1, Slide 38

Examples

  • USPS – Zip code lookup service on web site
  • HSBC – online banking service
  • NOKIA – web applications on mobile phones
  • BT – directory enquiries on web site
  • AA – online flight booking
  • Blackberry – PDA running Java applications Task - find a new example for me CS121/IS223 Week 1, Slide 39

Getting Started With Java

  • The Java 2 Platform Standard Edition (J2SE) Development Kit (JDK 6.0) includes the Java compiler (javac), the Java interpreter (JVM) & documentation, - available FREE from http://java.sun.com/javase/downloads/index.jsp
  • Eclipse SDK (v3.4)
    • available FREE from http://www.eclipse.org/downloads/index.php Install Java first Free Open Source Software! CS121/IS223 Week 1, Slide 40

Installing J2SE

  • Go to http://java.sun.com/javase/downloads/index.jsp
  • Follow instructions to download & install JDK6. update 11: - this software is FREE - you DON’T need to pirate software (& you shouldn’t)!
  • This is already done on the machines in the labs
    • so you DON’T need to do this again Follow the wizard CS121/IS223 Week 1, Slide 41

Installing Eclipse

  • Go to http://www.eclipse.org/downloads/index.php
  • Follow instructions to download & install Eclipse version 3.4 (Eclipse IDE for Java Developers): - this software is FREE - you DON’T need to pirate software (& you shouldn’t)!
  • This is already done on the machines in the labs
    • so you DON’T need to do this again Follow the wizard CS121/IS223 Week 1, Slide 42 - Your 1st^ cup will come in 2 flavours - Not making use of OO: - sufficient to practice basic programming concepts - like a latte, it goes down soooo smoothly - Making use of OO: - a taste of what is to come later in this class & go much further in CS - like an expresso, you acquire a taste over time, then nothing else will do!?

Your First Cup of Java

CS121/IS223 Week 1, Slide 43

Hello World in Java (Non-OO)

// Another Hello World Program – // Hello.java public class Hello { public static void main(String[] args){ System.out.println("Hello World!"); } } MUST call this file Hello.java Yes – it looks scary! Python: print “Hello World!” Must name the file after this CS121/IS223 Week 1, Slide 44

Note

  • All java programs have a similar basic structure
  • There are java coding standards you will learn about
  • Use indentation and blank space to lay out java code CS121/IS223 Week 1, Slide 45

Rules

  • All code must exist in a class public class Hello{ stuff; }
  • The filename you create to save your code must match the class name EXACTLY - Java is 100% case sensitive The keyword “class” must be written in lowercase The name given to the class must start with an uppercase letter You would need to call this Hello.java CS121/IS223 Week 1, Slide 46

Need to Have This Line

public static void main(String[] args)

  • Java always begins its execution at the main method in the class – main exists inside a class & there is only one main method String[] args is an array of strings – the command line arguments for a program (think of it as a shopping list for now!)
  • Ignore public static void until later on With Java, you have to take some things on trust for now Why? It is event- driven programming type variable name CS121/IS223 Week 1, Slide 47

Comments in Java

  • Comments are notes to help you & other people understand your programs – they are ignored by the Java compiler // This is a comment // in Java /* This is a comment in Java */ Good for single lines & in- line comments after code Good for multiple lines Use what you like – so long as you comment! CS121/IS223 Week 1, Slide 48

The Importance of Comments

  • Programming languages run on computers
  • However, humans also read them
  • Write your program so others can understand it
  • Use comments
  • In Java: // whatever THIS IS IMPORTANT - JUST DO IT!

CS121/IS223 Week 1, Slide 55

Key Points (Part A)

  • Programs tell the computer how to do something
  • Computers follow programs without thinking
  • Programs are written in a programming language – there are loads of these to choose from
  • The programming language code must be translated into a language the computer understands
  • The process of programming is systematic – write pseudocode to solve a problem, write code in a chosen programming language, compile/interpret/run

  • LOGO & Karel are great for learning
  • We take a step up with Java… CS121/IS223 Week 1, Slide 56

Before Next Time…

  • Install the Java & Eclipse on your own computers & try writing a few programs to print things out - please follow the Getting Started with Eclipse tutorial on my website
  • Reading – start reading Chapter 2 of the Java book:
    • this should add to already familiar background!
    • don’t worry if you are confused about the OO references for now … just follow the examples
    • can skip sections on applets & GUIs throughout the book – but if you can follow them & run the examples – excellent!!!
    • If you are stuck and confused - do not worry - we will go slow to start… CS121/IS223 Week 1, Slide 57

This Week’s Agenda (Part B)

  • Checking you all drank your first cup of Java
  • Exercise - cooking up some recipes
  • Getting going with Java
  • Assembling ingredients:
    • types, values, variables, declarations, assignment
  • Doing things with ingredients:
    • simple statements/expressions & operators CS121/IS223 Week 1, Slide 58

Details…

  • Variables, values & types
  • Assignment statements
  • Initialisation
  • Expressions & operators
  • Statements
  • Multiple assignment
  • Type casting/coercion
  • Simple input/output In Java! CS121/IS223 Week 1, Slide 59

Java Programs

  • 2 types of Java program
  • Java applications – a regular program that is meant to be run on your computer
  • Java applets – a little Java application that can be sent to another location on the Internet & run there (e.g. as part of a web page) All too seductive to start writing applets CS121/IS223 Week 1, Slide 60

A Java Application Example

From [Lewis & Loftus 2003] We will step through all these things later

CS121/IS223 Week 1, Slide 61

Explanation

  • Class definition – all java programs are defined in a class definition – a java program is not just a top down collection of statements
  • main is the place where the processing begins –– it is actually called a method
  • Main method always proceed by the words static main void
  • 2 lines of code inside the method call another method to print characters - here on the screen – println (print line)
  • Code for println is not defined in this program – it is part of the System.out object (java has big libraries of predefined code that you use all over the place … more in time) … it is the enormity of all this that can scare beginners …. So ignore this
  • Words java language – public, class, etc – are identifiers or reserved words – part of the CS121/IS223 Week 1, Slide 62

A Java Applet Example

From [Savitch 2004] CS121/IS223 Week 1, Slide 63

Why is Java Seductive for Students?

  • You can cut & paste Java code to do smart stuff quite quickly, without actually understanding OO or even understanding how to program: - students often end up not knowing how to write loops & do other core stuff!
  • If you want to learn Java – go on a professional training course
  • If you want to learn transferable programming skills – come to university (pick up C++, C#, use Python in an OO way, etc) CS121/IS223 Week 1, Slide 64

All Programming Languages

  • A specific syntax with a set of keywords that can be used to define data & express operations on that data
  • While the syntax of various languages differ – the underlying abstractions (concepts) are similar: - they support various data types (e.g. integers & strings) - they allow for the packaging of code into blocks (some call them functions, others call them methods)
  • Object Oriented programming languages (OOP) provide a way to group the data & methods together, then treat them as a whole (encapsulation)
  • No one best language for all problems
  • Each language has limitations/disadvantages CS121/IS223 Week 1, Slide 65

SPAM & Jam Layered Sandwich

  • National "Best SPAM Recipe" Competition 2002 Grand Prize Winner - Rachel Brooks
  • Ingredients:
    • 2 (8-ounce) cans reduced fat refrigerated crescent rolls
    • 1 (12-ounce) can SPAM Oven Roasted Turkey, thinly sliced
    • 4 slices Colby cheese
    • 4 slices Swiss cheese
    • 1/3 cup raspberry jam
    • Maple Mustard Sauce (see recipe below)
    • Powdered sugar Tip: SPAM Classic may be used in place of the SPAM Oven Roasted Turkey or in combination [Serves 6-8] Warning: recipe neither tested nor ever likely to be eaten by me! Nested recipe CS121/IS223 Week 1, Slide 66

Method

  • • Heat oven toSeparate dough (^375) into 4° long rectangles
  • • Place rectanglesFirmly press perforations to seal - rectangles should not touch when baking crosswise on 1 large or 2 small un-greased cookie sheets
  • • Bake forCool on pans8-12 for 5 minutesminutes until golden brown
  • Top one crust with half of SPAM and Colby cheese
  • • Place second crust on top of the cheeseTop evenly with other half of SPAM and Swiss cheese
  • • Place third crust on top of the cheese - spreadTop with fourth crust evenly with raspberry jam
  • Return layered sandwich to the oven and heat for 15 minutes or until filling is hot
  • • LetSprinkle stand sandwich with powdered sugar, if desired, and slice into 1-inch pieces 5 minutes before slicing
  • If desired, serve with Maple Mustard Sauce FULL OF AMBIGUITY!!!

CS121/IS223 Week 1, Slide 73

Clarification

  • Java programs are compiled into Java bytecode – code for a virtual processor called the Java Virtual Machine (JVM)
  • A Java bytecode interpreter (some people call this the JVM) translates the bytecode into the machine code for any particular computer & executes this code
  • Compile once – > distribute -> execute on any real processor that can run a JVM Cost of portability = speed Task: Write a list of what you consider would be pros and cons - do some research CS121/IS223 Week 1, Slide 74

How to Write a Program in Java

  • Use a text editor or IDE to type in the source code:
    • in Java – we will use Eclipse
  • Save the source code as a file:
    • in Java – we will call it FileName.java
  • NOW… what we do next is IMPORTANT!! Java source code MUST always end with .java and start with a capital letter - it is a case sensitive language Integrated Development Environment CS121/IS223 Week 1, Slide 75

How to Run a Program in Java

Aafter we have saved the file, we compile it using the Java compiler (called javac) - type: javac FileName.java

  • If it compiles ok, then an intermediate file is produced called FileName.class (this is Java bytecode) – you can copy & execute a .class file on any platform
  • We need to execute (run) this intermediate file as a separate step – type: java FileName - the command java runs the JVM which simulates the virtual processor
  • If it doesn’t compile ok, we have errors to fix CS121/IS223 Week 1, Slide 76

Summary

FileName.java FileName.class Running program Compile: javac FileName.java Interpret: java FileName Source code Bytecode Fix compile time errors Fix runtime errors This is what you would do to run Java from the command line. Eclipse makes this easier for you Runs machine code CS121/IS223 Week 1, Slide 77

  • Your 1st^ cup will come in 2 flavours
  • Not making use of OO:
    • sufficient to practice basic programming concepts
    • like a latte, it goes down soooo smoothly
  • Making use of OO:
    • a taste of what is to come later in this class & go much further in CS
    • like an expresso, you acquire a taste over time, then nothing else will do!?

Back to Your First Cup of Java

CS121/IS223 Week 1, Slide 78

Hello World in Java (Non-OO)

// Another Hello World Program – // Hello.java public class Hello { public static void main(String[] args){ System.out.println("Hello World!"); } } MUST call this file Hello.java Yes – it looks scary! Python: print “Hello World!” Must name the file after this

CS121/IS223 Week 1, Slide 79

Hello World in Java (OO - Hybrid)

// Yet Another Hello World Program – Hello.java public class Hello{ public void printHello() { System.out.println("Hello World!") ; } public static void main(String[] args){ Hello hello = new Hello() ; hello.printHello(); } } You use // to make comments in Java You use matching braces {} to group statements in Java You use semi-colons to end statements in Java; Although indentation is used here – it is only used to make the code clearer – it is not part of Java syntax CS121/IS223 Week 1, Slide 80

Hello World in Java (OO - Hybrid)

// Yet Another Hello World Program – Hello.java public class Hello{ public void printHello(){ System.out.println("Hello World!"); } public static void main(String[] args){ Hello hello = new Hello(); hello.printHello(); } } This statement is the statement we actually want to execute Everything else is java window dressing – but you do need it! In Java it is called println & we also see the dot notation proceeding it … …it requires knowing about some other things to work CS121/IS223 Week 1, Slide 81

Hello World in Java (OO - Hybrid)

// Yet Another Hello World Program – Hello.java public class Hello{ public void printHello() { System.out.println("Hello World!"); } public static void main(String[] args){ Hello hello = new Hello(); hello.printHello(); } } This is sort of like a function, called a method in Java (used to organise code) These public qualifiers are to do with visibility OO bits & bobs User defined type CS121/IS223 Week 1, Slide 82

Hello World in Java (OO - Hybrid)

// Yet Another Hello World Program – Hello.java public class Hello { public void printHello(){ System.out.println("Hello World!"); } public static void main(String[] args){ Hello hello = new Hello(); hello .printHello(); } }^ hello is a reference to an object of the class Hello (an instance) – created in the statement above Classes & objects This is the name of a class (think of it as a user- defined type for now) – it is a template that describes what a hello object is & what it can do CS121/IS223 Week 1, Slide 83

Hello World in Java (OO - Hybrid)

// Yet Another Hello World Program – Hello.java public class Hello{ public void printHello(){ System.out.println("Hello World!"); } public static void main(String[] args) { Hello hello = new Hello(); hello.printHello(); } } The code starts here – accept it as is for now When you run the program it creates a hello object & asks the hello object to do something, namely printHello() Starting point CS121/IS223 Week 1, Slide 84

Hello World in Java (OO)

// Yet Another Hello World Program // HelloWorld.java public class HelloWorld{ public Hello static hello = void new main(String[] Hello(); args){ hello.printHello(); } } // A Hello class for Yet Another Hello World Program // public Hello.java class Hello{ public void printHello(){ System.out.println("Hello World!"); }^ } Must call this file HelloWorld.java Yes – it looks VERY scary! MUST call this file Hello.java

2 SEPARATE FILES - LINKED DEPENDENCY

Write, save, compile Hello.java, then HelloWorld.java

CS121/IS223 Week 1, Slide 91

Why So Complicated?

  • Java uses classes & objects to structure its programs - they are the building blocks for writing an OO program
  • Java comes with masses of built-in class libraries & lots of exceptions that you may need to know about to do many simple things
  • It is a BIG language; it takes more time We’ll take one sip at a time… Again, one sip at a time… CS121/IS223 Week 1, Slide 92

Ingredients

  • Variables, values & types
  • Assignment statements
  • Initialisation
  • Expressions & operators
  • Statements
  • Multiple assignment
  • Type casting/coercion
  • Simple input/output CS121/IS223 Week 1, Slide 93

Variables, Values & Types

  • Variables are particular shaped containers
  • Variables can hold a value (so long as it is of the right shape)
  • The shapes are called types CS121/IS223 Week 1, Slide 94

Variables & Values in Java

  • Variables implemented as memory locations
  • Values implemented as 0’s & 1’s
  • Values placed in memory locations
  • The Java compiler needs to know the type of every variable
  • In Java, every variable must be declared before it can be used (i.e. each variable is bound to a type) CS121/IS223 Week 1, Slide 95

Variables

  • A variable is a name that refers to a value
  • Why have variables?
    • 5 tins of spam in stock
    • sell 1 tin of spam
    • 4 tins of spam now in stock
  • Programs manipulate & change values – we need to keep track of these values over time

variable spamTins = 5 value

CS121/IS223 Week 1, Slide 96

Declaration of Variables in Java

  • You can’t just use variables
  • In Java, you have to explicitly declare your variables before you can use them – this allocates space for the variable in memory & specifies its type (how much space)
  • Say we wanted to use an integer variable, it would be declared like this in Java: int spamTins; type variable name (identifier) Java statements end with ; Not unlike introducing friends

CS121/IS223 Week 1, Slide 97

More…

  • Values can be constant or changeable … that’s why we call it a variable
  • A special type of variable where the value does not change is called a constant
  • A variable name is called an identifier
  • When we put a value in a variable, we make an “assignment” CS121/IS223 Week 1, Slide 98

Another Analogy

  • Think of a variable as a cup – a container – it holds something
  • Java – once a coffee cup, always a coffee cup CS121/IS223 Week 1, Slide 99

Java Style

  • Write code in a style that helps to prevent syntactical mishaps
  • Write code in a style that makes syntactical mishaps glaringly obvious
  • Your secret weapon:
    • consistent code layout - white space, indentation & braces
    • useful naming conventions
    • comments (^) Called defensive programming CS121/IS223 Week 1, Slide 100

Rules for Naming Variables in Java

  • Helpful – suggest the data they hold
  • Contain only letters, digits 0-9 & underscore (_)
  • First character cannot be a digit
  • Can’t contain spaces or other characters
  • No official limit to name length
  • Case sensitive – uppercase & lowercase are different characters
  • Convention to punctuate using uppercase (myVariable)
  • Can’t use reserved words as variable identifiers (e.g. if, boolean, etc) CS121/IS223 Week 1, Slide 101

Exercise

  • Which of the following are valid variable names in Java:
  1. count
  2. 1stGame
  3. boolean
  4. MyName
  5. numberOne
  6. sum.java
  7. my_choice
  8. hello@world Are myCounter & mycounter the same variable? CS121/IS223 Week 1, Slide 102

Types

  • Types are fundamental to programming languages
  • A type is a set of rules to interpret a value stored in a memory location (i.e. the value of a variable)
  • Each data type is characterised by:
    • the basic values it can hold
    • the operations that can be defined on it

CS121/IS223 Week 1, Slide 109

Class Types in Java

  • Non primitive types exist & are important
  • Class types are abstractions created from primitive types (like a bank account, an address, etc)
  • A class type that is widely used in java is String – to represent a sequence of characters
  • There is a class String that you use to implement strings, so strings are actually objects, which requires a bit of extra code to use “This is a string” - strings are literal values CS121/IS223 Week 1, Slide 110

So, …

  • Variables must have a type & a name
  • Can hold primitives or class types (references to objects)
  • Assignment (assigning a value to a variable):
    • type a literal (x = 10)
    • assign the value of one variable to another (x = y)
    • use an expression combining both the above (x = y * 10) CS121/IS223 Week 1, Slide 111

Declare & Initialise Your Variables

int count = 100;

  • Declares count to be of type int & gives it an initial value of 100 at the same time – this is an example of an assignment statement in Java
  • You have to explicitly initialise your variables in Java (i.e. declare them & give them an initial value) or your program will not compile – why???
  • 100 is now a literal value of type int that can directly be used in your program (100 is always 100) The assignment operator Assigns a value to a variable Variables MUST HAVE a type in Java Type Name Value CS121/IS223 Week 1, Slide 112

CORE CONCEPT - Assignment

  • Common to programming languages:
    • all programs manipulate data ( values)
    • lots of different types for these values
    • not all types are supported in every language
    • some languages are better at handling certain types than others
    • every language has variables (in some form or another) in which to place these values
    • names ( identifiers) are assigned to variables – this is called declaring variables
    • when learning a programming language – you need to find out what types of variables it supports & how they are used
    • we make assignments…

int spamTins = 5

CS121/IS223 Week 1, Slide 113

More Assignment in Java

  • After you have initialised a variable, you can change its value using another assignment statement: count = 99;
  • This overwrites the old value of count (which was 100) with the new value of 99
  • In Java – we do these 2 things separately: int count = 100; (initialise) int count; count = 99; (assign a new value) count = 99; Different ways (^) CS121/IS223 Week 1, Slide 114

What Happens Without Introductions?

No! Yes!

CS121/IS223 Week 1, Slide 115

Examples of Declaration & Initialisation

  1. byte small = 2;
  2. short counter = 100;
  3. int mediumCounter = 9999;
  4. long bigCounter = 100000000000000000;
  5. float number = 45.67;
  6. double bigNumber = 45.6755599992002;
  7. char letter = ‘a’;
  8. boolean complete = false;
  9. String greeting = “Hello World!” greeting is an object of class String CS121/IS223 Week 1, Slide 116

Exercise

  • Do the following declarations & initialisations in Java:
  1. Set the value of sleepy to false
  2. Set the value of myCounter to – 10
  3. Set the value of pi to 3.
  4. Set the value of greeting to “Not today thanks”
  5. Set the value of dummyValue to 999
  6. Set the value of distance to 345288
  7. Set the value of initial to ‘Z’
  8. Set the value of finished to true To do this you need to pick a type & write assignment statements - do this in code CS121/IS223 Week 1, Slide 117

Exercise Cont…

  • Now change the values of the variables you have just initialised:
  1. Make sleepy true
  2. Make myCounter +
  3. Make pi 3.
  4. Make greeting “Ready to play”
  5. Make dummyValue 1999
  6. Make distance to 345288
  7. Make initial ‘W’
  8. Make finished false To do this you need to write assignment statements - write separate statements to do this in your code CS121/IS223 Week 1, Slide 118

Doing Things With Ingredients

  • A program is a series of instructions (code describes these instructions)
  • When a computer runs code, it performs these instructions
  • Instructions:
    • statements
    • expressions
    • functions & beyond… CS121/IS223 Week 1, Slide 119

Statements & Expressions

  • So far, we have some simple statements that perform a single operation: - println statement - assignment statements
  • Expressions combine variables, values & operators: 2 + (^3) spamTin - 1 value (^) operator value (^) variable value operator Input & Output CS121/IS223 Week 1, Slide 120

Arithmetic Operators

  • Addition +
  • Subtraction -
  • Multiplication *
  • Division /
  • Modulo % (remainder) Remember from math: - order of precedence? - role of parentheses? You will meets lots more operators… Make sure you understand the difference between unary operators & binary operators PEMDAS M&D equal; A&S equal (Please excuse my dear, Aunt Sally) – so apply left to right