comp-202: foundations of programmingcs202/2015-05/web/lectures/...output (more on printing)...

Post on 30-Mar-2020

5 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

COMP-202: Foundations of Programming

Lecture 2: Variables, and Data Types

Sandeep Manjanna, Summer 2015

Announcements

• Midterm Exams on 4th of June (12:35 – 14:35)

• Room allocation will be announced soon

• Final Exams on 26th of June.

• Timing and Rooms will be announced soon

• McGill ID is necessary for taking exams.

• Assignment 1 released.• Due Date : 17th of May (@ 23:30)

Review

• Programming language

• Data representation in computers

• Compilers and Interpreters

• Errors and Debugging

Review

public class Hello

{

public static void main(String[] args)

{

System.out.println("Hello, there!!");

}

}

• What is the Class Name?

• Importance of main method?

• Can I replace ‘main’ with some other word in this example?

• Which part of this program is a statement?

• What does this program do?

• Every Statement should end with a semi-colon ( ; ).

This Lecture

� Variables

� Data Types

� Strings

Handling Output

Output (More on Printing)

System.out.println(“Hello, world.”);

• The phrases appearing in “ ” are called Strings (string of characters).

• ‘println’ is a short form for print line. This makes the next statement go to a newline.

Output (More on Printing)

• Guess the output of :public class Hello

{

public static void main(String[] args)

{

System.out.print(“Hello, there !!”);

System.out.println(“How are you doing ?”);

System.out.println(“What are you up to?”);

}

}

Hello, there !!How are you doing ?

What are you up to?

Escape Characters

• Use an escape sequence for punctuations or spacing.

• \n � NewLine

• \t � Tab

• \” � To have double quotes inside a string

• \\ � To escape the escape character!!!!!

Output (More on Printing)

• Guess the output of :

public class Hello

{

public static void main(String[] args)

{

System.out.println(“Hello, there !! \t How are you doing ? \nWhat are you up to?”);

}

}

Hello, there !! How are you doing ?

What are you up to?

Comments

• Comments are the annotations that can be included in your code about what it does so that it is easy to understand.

• Examples:

Single-line Comments

// This will be ignored by the compiler

Multi-line Comments

/* So will this, if you need to write a comment that spans multiple lines. */

/* It is important to comment, especially in tricky parts of the code. But don't go overboard and comment every single line!

*/

Variables

Input

• To take input from the user

We need,

1. A place to store it for further computations

2. A way to take input from the user

What are Variables?

• Remember this from high-school algebra?�� � ���=

What are a and b?

• From geometry:

Area of a circle = ��

What is r?

• In plots below:

�� � �� � 2��

What are x and y?

Variables in Java

• A variable is a place in memory reserved for storing a value. In Java, we give each variable a name, to make it easier to identify and a type to keep track of the kind of data we are storing.

String myName;

int counter;

• Essentially, you could say a variable is a typed label for a space of memory.

Variable Declaration

• These statements declare variables of various types. What are the types and the names?

String myName;

int myAge;

double myHeight;

boolean isStudent;

• You can name a variable anything that you want, as long as it only contains letters, numbers, and _, and doesn’t start with a number.

• But you need to choose a clear, simple and appropriate name for readability (and full marks!)

• With variable declaration, you are declaring to the compiler that you will be using a variable with specified name in the program.

Keywords

• There is a set of words that have specific meaning in Java programming. These words are referred to as Keywords.

• The Keywords contribute to the syntax of the Java program.

Example : class, public, int, char, etc.

• Hence, we cannot use these keywords as names for variables or classes or any other identifier.

Setting the Value of a Variable

• The assignment operator = sets the variable on the left-hand side to the value on the right-hand side.

String myName;

myName = “Sandeep";

Or combined (in single line):String myName = “Sandeep";

• The expression can be complicated, so it will be evaluated for its value first.

• While expressing the variable and its value on paper, usual convention is to write:

myName Sandeep

Assignment Examples

int x;

int y;

x = 10;

y = 100 + 10;

x = y + 3;

• What are the values of x and y at each line above?

• What happens if we try to use a variable we haven’t declared, like z?

• Assignment operation always has a variable on LHS and an expression or a constant on RHS.

3 = x + 2 � is a wrong usage of assignment.

Declaring and Assigning

• Declaring a variable:

<type> <var_name>;

int numStudents;

• Assigning a value to the variable:

<var_name> = <value>;

numStudents = 125;

• Doing both at the same time:

<type> <var_name> = <value>;

int numStudents = 125;

Printing Variables

• To print a variable with System.out.println:

int numStudents = 125;

System.out.println(numStudents);

System.out.print(“Number of Students per TA = ”);

System.out.println(numStudents/3);

Try it out

• Write a piece of code that swaps the value of two intnumbers x, and y.

• So, if x is 5 and y is 4 before the piece of code is run, x is 4 and y is 5 after.

• Fill in the … :

• int x = 5;

• int y = 4;

• …

• // by here, x is 4 and y is 5

Data representation in Binary

Data in Computers

• Remember that all information in a computer is represented as a number???

• Text as numbers: T h i s [space] …….

84, 104, 105, 115, 32, ……..

• Images as numbers:Store (R,G,B) values of each pixel.

A pixel could be 37-red, 76-green and 125-blue and it would then look like this -

• Music as numbers:Store the amplitude of the sound wave over time.

But the numbers used to represent these data are not in Decimal

system. Instead Binary numbers are used to store these data.

Decimal Numbers

• What does writing the number 2015 mean?

• Ones: 5

• Tens: 1

• Hundreds: 0

• Thousands: 2

• So,

• 2015 =

• 2 × 10� � 0 × 10� � 1 × 10� � 5 × 10�

Binary Numbers

• Base is 2, not 101101010 = 1 × 2� � 1 × 2� � 0 × 2� � 1 × 2�

�0 × 2� � 1 × 2� � 0 × 2�

• To convert to decimal, just compute the sum!1101010� = 1 × 2� � 1 × 2� � 0 × 2� � 1 × 2�

�0 × 2� � 1 × 2� � 0 × 2�

= 1 × 64 � 1 × 32 � 0 × 16 � 1 × 8

�0 × 4 � 1 × 2 � 0 × 1

= 64 � 32 � 8 � 2= 106��

Decimal to Binary

• Easiest way: parity checks and divisions by 2e.g., What is 53�� in binary?

��

�= 26�1

��

�= 13�0

��

�= 6�1

�= 3�0

�= 1�1

�= 0�1

53�� = 110101�

Try it out

• Perform the following conversions

• Binary to decimal:

111 10001 10010011

• Decimal to binary:

24 179 3258

Why Binary???• Binary number system has two possible digits: 0 and 1.

• A switch in a circuit can take two states : ON and OFF. In computer domain, each such switch is referred to as a bit.

• ON is interpreted as 1 and OFF is interpreted as 0.

• Thus with two bits, we can have 4 permutations,(Decimal)

OFF OFF 0 0 0

OFF ON 0 1 1

ON OFF 1 0 2

ON ON 1 1 3

• How many bits needed to represent 8 numbers?

• In general, with ‘n’ bits one can represent : 2� numbers.

3

Basic Data Types

Some Basic Variable Types

int Integer values

long Long integer values

float Real numbers

double Real numbers, with more precision

boolean True or false

char One character

More Types

byte Can only store integers between -128 and 127

short Can only store integers between-32768 and 32767

• Difference between byte, short, int, long – is the number of bits (binary digits) used.

• Difference between float and double is also because of the number of bits.

Some Basic Variable Types

Primitive Data Types Size in bytes Range

byte 1 -128 < x < 127

short 2 -32,768 < x < 32,767

int 4 -231 < x < 231 - 1

long 8 -263 < x < 263-1

float 4 (approx) +/- 3.4 * 1038

double 8 (approx) +/- 1.8 * 10308

boolean Represents only 1-bit

information. Size is not precisely

defined.

true and false

char 2 0 < x < 216 - 1

Mismatching Types

• If you try to store something of type X in something of type Y, the Java compiler will complain.

int x;

x = "Hello";

• What are the types of "Hello" and x?

Why Does Java Care?When we write

int x;

• Java needs to set aside enough memory to store one integer value. If you try to store a String, it doesn't know whether it will fit or not!

• Also, ensuring type consistency helps us debug code. x = "Hello"; in the previous slide is obviously wrong!

• The same sequence of bits that encode an int would be meaningless if decoded as a String.

int

• The type int represents an integer in range of:

[−2��, 2��– 1], or

[−2147483648, 2147483647].

• An int takes up 32 bits = 4 bytes in memory (1 byte has 8 bits).

• So, there are 2�� possible values that can be represented.

• Half of these are for negative numbers, and one more spot is taken up by zero.

double• The type double represents a real number with fractional

values.

• They cannot store an infinite number of digits (e.g., pi). They can only store to a limited precision.

double almostPi = 3.14159; // can only store

// some of the digits

• If you write .0 after an integer constant, it will be stored as a double.

int x = 3.0;

int x = 3;

double x = 3.0;

Operations between an intand a double

• A Mathematical operation between an int and a double will result in a double value.

2.0 * 5 = 10.0 � A floating point multiplied with an integer will result in a double.

1 / 2 = 0 � Because both 1 and 2 are integers. The result will be an integer (the floating point will be truncated).

1.0 / 2 = 0.5 � One of the operands is a floating point. Hence the resultant will be floating point.

(double)3 + 5 = 8.0 � One can convert an integer into double by using a type cast technique as shown above.

Trial Examples

• What is the type and value of the Result?

Value Type

• 2.5 * 2 =

• 5 / 2 =

• 5.0 / 2 =

• 1 + 2.0 =

5.0 double

2 int

2.5 double

3.0 double

Casting

• You can force a conversion to the type you want, even if you lose information! This is called type casting or just casting.

• Write (data_type) before the expression to convert.

int x = (int) 7.5;

int y = (int) -7.5;

40

Casting is Temporary

• Just asdouble x = 3.5;

double y = -x;

does not change x, neither does

double x = 3.5;

int y = (int) x;

• x is still a double.

char

• A char occupies 2 bytes (16 bits).

• A character set is an ordered list of characters, where each character corresponds to a unique number.

• A char stores a single character from the Unicode character set.

char gender;

gender = 'M';

Java Unicode• As mentioned before, all the characters have a number

associated with them. This number is called Unicode.

• Look up at : http://www.ssec.wisc.edu/~tomw/java/unicode.html

• Thus ‘char’ datatype behaves like an integer as it stores an integer.

Typecasting Example:

int x = 65;

char a = (char) x;

char addition:

char a = 'A';

char b = 'B';

char d = (char)(c+b);

boolean

• A boolean stores things that are either true or false.

• boolean areYouOnFacebook;

• areYouOnFacebook = false;

Strings and

String Operations

String

• A String stores a sequence of char's. It is a more complex type than the others mentioned. Why?

• How many bits do you need to store a String?

• We've seen how to assign text to a String:• String helloWorld = "Hello, World!";

String Operations

• String comparisonAre two strings the same?

• String concatenationPut together multiple Strings

• String lengthGetting the length of a String

String Comparison

• Check whether two Strings are equal:

someString.equals(otherString)

• Examples:"Abc".equals("Abc")

"Abc".equals("A")

"ABC".equals("Abc")

Can also compare String variables• String myName = “Marley";

• String yourName = "Bob";

• System.out.println(myName.equals(myName));

• System.out.println(myName.equals(yourName));

String Concatenation

Put together two Strings with the + operator.

firstString + secondString

System.out.println("This is " + "one sentence.");

String secondString;

secondString = "COMP-202";

System.out.println("This is " + secondString);

secondString = “Not bad";

System.out.println("This is " + secondString);

String ConcatenationWe can also concatenate numbers and variables with strings.

“Hello” + 23 � Hello23

“Hello” + 123 + “Numbers” � Hello123Numbers

int a = 5;

double b = 2.3;

boolean c = false;

String s = “Hello” + a + b + c;

System.out.println(s);

Hello52.3false

String Length

• Get the length of a String:someString.length( );

• Examples:"Abc".length( )

String myName = “Marley";

String yourName = "Bob";

int bothLength = myName.length() + yourName.length();

• There are more examples of methods provided by Java so that we don’t need to write our own methods to do these common operations.

• Please refer : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Warm-Up

• What type of variable would you use to store the following?

• The number of school days in a year.

• The cost of a meal at a restaurant.

• Name of the course instructor.

• A PIN for an ATM card.

• Whether it snowed on January 3rd.

• Grade of a student.

Input

• How do we take input from the user?

We need,

1. A place to store it for further computations

2. A way to take input from the user

Inputs from the user

• How to read input from the user?

• Use the following magical (for now) incantation:

• At the top of the file:

import java.util.Scanner;

• In the main method:

Scanner scanner_variable = new Scanner(System.in);

• Then, call this method to read a line:

scanner_variable.nextLine();

• Problem: need to store it in a variable!

Inputs from the userimport java.util.Scanner;

public class Repeater

{

public static void main(String[] args)

{

System.out.println("Say something!");

// create a Scanner to read some input

Scanner scanner = new Scanner(System.in);

String s = scanner.nextLine();

System.out.println(s);

}

}

We will see more of Scanner in classes and assignments.

How do I look up about Java standard libraries like Scanner ???

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Java docs are very useful to look up about any standard library in java.

• Now we know how to read a String from standard input.

• How to read other data types???

• For the basic data types, use .next<typename>:

scanner.nextBoolean()

scanner.nextByte()

scanner.nextInt()

scanner.nextDouble()

Inputs from the user

Try it out

• Write a program that asks for a temperature in Fahrenheit, then computes and displays the equivalent in Celsius.

celsius = (fahrenheit – 32.0) * 5.0 / 9.0

• Hint: break it down into the following steps:1. Set up main method in a class

2. Get the Scanner working

3. Implement the conversion formula

4. Display the output

Try it out

import java.util.Scanner;

public class TempConverter {

public static void main(String[] args) {

System.out.println("Enter temperature in F:");

Scanner scanner = new Scanner(System.in);

// TODO: read temperature and convert

System.out.println("The temperature in C is:");

// TODO: display new temperature

}

} celsius = (fahrenheit - 32.0) * 5.0 / 9.0

Summary

� More printing options

� Variable (Declaration and Assignment)

� Binary Numbers

� Data Types

� Strings

� Reading input (Scanner)

top related