Download Data types and variables

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Data types and variables
today



My First program
Variables
Data types
Java-Why is it special?

Java is an object-oriented language.



Programming methodology that views a program
as consisting of objects that interact with one
another by means of actions (called methods)
Java programs are portable between
machines
Java is accompanied by a rich set of libraries
that allow you to create graphics, interact
with databases, communicate overnetworks,
etc.
Byte-Code and the Java Virtual
Machine

The compilers for most programming languages
translate high-level programs directly into the
machine language for a particular computer


Since different computers have different machine
languages, a different compiler is needed for each one
In contrast, the Java compiler translates Java
programs into byte-code, a machine language for a
fictitious computer called the Java Virtual Machine

Once compiled to byte-code, a Java program can be used
on any computer, making it very portable
Byte-Code and the Java Virtual
Machine

Interpreter: The program that translates a
program in Java byte-code into the machine
language for a particular computer when a
Java program is executed. The interpreter is
also known as the Java Virtual Machine (JVM)


The interpreter translates and immediately
executes each byte-code instruction, one after
another
Translating byte-code into machine code is
relatively easy compared to the initial compilation
step
Platform independent

Java compiler translates a Java program
into Java byte-code

Java bytecode is not tied to any particular
processor type

Java interpreter executes the Java bytecode.

A Java interpreter needed for each
processor type.
Translate Java code to
Machine Code

Compiler
Java code -------- Java byte-code

Interpreter
Java byte-code --- Machine code
Java concepts


Method : group of programming
statements that is given a name.
Class: named group of related methods.
My First Program
public class MyFirstClass {
public static void main ( String args[] ) {
System.out.println( “Hi there” );
System.out.println( “Enjoy the show!” );
}
}
main method
public static void main ( String args[] )
{
System.out.println( “Hi there” );
System.out.println( “Enjoy the show!” );
}
How can a program perform
output?
System.out.println( “Hi there” );
System.out.println

Java programs work by having things
called objects perform actions


System.out: an object used for sending
output to the screen
The actions performed by an object are
called methods

println: the method or action that the
System.out object performs to print
specified character string to the screen
System.out.println

Invoking or calling a method: When an
object performs an action using a method
Also called sending a message to the object
 Method invocation syntax (in order): an object, a
dot (period), the method name, and a pair of
parentheses
 Arguments: Zero or more pieces of information
needed by the method that are placed inside the
parentheses
System.out.println("This is an argument");

blocks
{
System.out.println( “Welcome!” );
System.out.println( “Enjoy the show.” );
}
Comments

Annotation (notes) about the code.



Computer only executes code.
Comments are for human readers of our
code.
How/what/why about the code that follows
(so comments appear before the code that
they describe).
Comments

We need a way to tell the compiler that this is
a comment and not code (so the compiler can
ignore our comment).
// This is a one line comment.
/*
This is a block comment.
It may span multiple lines.
*/
/* Or it may be just a single line. */
My First Program
/* My first Java program */
public class MyFirstClass {
public static void main ( String args[] ) {
System.out.println( “Hi there” );
System.out.println( “Enjoy the show!” );
}
}
Error Messages

Bug: A mistake in a program


The process of eliminating bugs is called
debugging
Syntax error: A grammatical mistake in
a program

The compiler can detect these errors, and
will output an error message saying what it
thinks the error is, and where it thinks the
error is. E.g. a missing semicolon!
Tip: Error Messages

Run-time error: An error that is not detected
until a program is run


The compiler cannot detect these errors: an error
message is not generated after compilation, but
after execution
Logic error: A mistake in the underlying
algorithm for a program

The compiler cannot detect these errors, and no
error message is generated after compilation or
execution, but the program does not do what it is
supposed to do
Variables and Data types


In math we may say, “Let x be an
integer.” Or, “Let a be a real number.”
How can we do this in our code?
What is a variable?

The name of some location in memory
used to a hold a data value.
Data types

Data may be of different types


Different types of data require different amounts of memory
Some data types:




int (an integer)
double (a real number)
String (a string of characters)
char (a single character)
More later!
Variable declaration

So how do we say, “Let x be an integer?”





int x;
This is a variable declaration.
 Instructs the compiler to reserve a portion of memory
space large enough to hold a particular type of value
 Indicates the name by which we refer to that location
x is the name of the variable. We made up this name.
int is a keyword or reserved word. It is part of the Java
language. We can’t use int for anything else (like variable
names).
We may (and need) only declare x once.
Variable declarations


Every variable in a Java program must be declared
before it is used
Variables are typically declared just before they are
used or at the start of a block (indicated by an
opening brace { )
Variable declaration

“Let x and y be integers.”

int x;
int y;

Or

int x, y;

Variable declaration

“Let x be an integer and height be a
real number.”

int x;
double height;

What value does x have?

Variable declaration and
assignment (=)
//declare vars
int x;
String name; //note uppercase ‘S’
//assign initial values
x = 1;
name = “fred”;
Variable declaration and
assignment
//declare vars
char ch;
//assign initial values
ch = ‘x’;
Variable declaration and
assignment
//declare vars
int x;
//assign initial values
x = 12;
Variable declaration and
assignment in one
int x = 12; //two steps in one
Tip: Initialize Variables


A variable that has been declared but that
has not yet been given a value by some
means is said to be uninitialized
In certain cases an uninitialized variable is
given a default value


It is best not to rely on this
Explicitly initialized variables have the added
benefit of improving program clarity
Tip: Initialize Variables

The declaration of a variable can be
combined with its initialization via an
assignment statement

int count = 0;
double distance = 55.5;
char grade = 'A';
Note that some variables can be initialized and
others can remain uninitialized in the same
declaration
int initialCount = 50, finalCount;
Primitive Data Types

Basic types in java are called primitive types

Integer types:




Floating point types:




int: most common
short, byte: for small integers
long: for huge values
float: roughly 7 digits of precision
double: rouhly 15 digits of precision
char: a single character
boolean: (true or false)
Primitive Types
Valid variable names





Starts with: a letter (a-z or A-Z), dollar
sign($), or underscore(_)
Followed by: zero or more letters, dollar
signs, underscores, or digits(0-9)
Case-sensitive! Uppercase and lowercase are
different. Rate, rate, and RATE are the
names of three different variable
Cannot be any of the reserved names
Can theoretically be of any length
Variable names (valid or
invalid?)







$$1_1
numberOfBeans
public (reserved word)
1day
peanutbutter&jelly
aZ_b
INT
Good variable names




Do not use $
Avoid names that are identical other
than differences in case
Use meaningful names
Avoid excessive length
Naming Conventions

Start the names of variables, methods, and
objects with a lowercase letter, indicate
"word" boundaries with an uppercase letter,
and restrict the remaining characters to digits
and lowercase letters
topSpeed

bankRate1
timeOfArrival
Start the names of classes with an uppercase
letter and, otherwise, adhere to the rules
above
FirstProgram
MyClass
String
Identifiers

Identifier: The name of a variable or
other item (class, method, object, etc.)
defined in a program

A Java identifier must not start with a digit,
and all the characters must be letters,
digits, the underscore symbol, or the dollar
sign
Identifiers

Keywords and Reserved words: Identifiers that have
a predefined meaning in Java

Do not use them to name anything else. Examples:
public
class
int
double
if

void
for
static
private
Predefined identifiers: Identifiers that are defined in
libraries required by the Java language standard

Although they can be redefined, this could be confusing and
dangerous if doing so would change their standard meaning
System
String
println
Next time:

Assignment and Arithmetic expressions