0% found this document useful (0 votes)
3 views53 pages

Cs211 01 Java Basics

The document provides an overview of Java programming basics, including object-oriented programming concepts, variables, data types, and control flow. It outlines the structure of a Java program, the types of tokens used in Java, and the different kinds of variables. Additionally, it discusses Java's portability, its development environment, and the distinctions between various Java editions.

Uploaded by

Cb Major
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views53 pages

Cs211 01 Java Basics

The document provides an overview of Java programming basics, including object-oriented programming concepts, variables, data types, and control flow. It outlines the structure of a Java program, the types of tokens used in Java, and the different kinds of variables. Additionally, it discusses Java's portability, its development environment, and the distinctions between various Java editions.

Uploaded by

Cb Major
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Java Basics

Variables, Data Types, Control Flow


CS 211 @ GMU

Dr. Brian Hrolenok - Department of Computer Science - George Mason University

1
Outline

Object Oriented Programming concepts and Java background


Java Language Basics
Variables and Data Types
Control Flow

Installing Java on your system:


https://cs.gmu.edu/~marks/211/textbook/01-getting-started.pdf

2
What is programming?
Computers are extremely fast, precise, and dumb

• Telling a computer what to do


• More formally: "Writing a sequence of instructions for performing a speci c task
in a format that a computer can process unambiguously"

• We call the sequence of instructions we give to the computer a program


• More broadly, any process for solving a speci c task we call an algorithm, which can
have a variety of forms

• A format that a computer can understand is called a programming language


• Important: there's always more than one way to solve a problem. Di erent
programming languages have di erent approaches to problem solving
3
ff
fi
ff
fi
Procedural vs Object Oriented
Approaches to programming

Procedural Object-Oriented
• Describe the process that solves the • Describe the di erent pieces
problem (objects) of the problem, and how
they interact
• Separate the data from the
operations on that data • Separate interactions between
objects and internal representation
• Unit of programming is the function
(note, this is not functional • Unit of programming is the object
programming) (class)

4
ff
Procedural vs Object Oriented
Example: ATM

Procedural Object-Oriented
Possible functions Possible objects
• withdraw() • Customer
• deposit() • Account
• transfer() • Bank

5
What is Java?

• An object-oriented programming language developed by Sun


Microsystems - now owned by Oracle

• Created out of a research project started by James Gosling in 1991


with a "C++ style" syntax

• Five principles
1. Simple, Object-Oriented, Familiar

2. Robust and Secure


James Gosling in 2008
3. Portable* Photo credit: Peter Campbell / Wikipedia

4. Fast

5. Interpreted, threaded, dynamic**

6
What is Java?
Portability

The development environment for Java has two parts: the Java compiler and the
Java interpreter / virtual machine (VM)

• Compiler
• Processes Java source code (.java les)
• Generates bytecode (not machine code) in a separate .class le
• Virtual machine
• Processes bytecode (.class les)
• Executes (runs) the program
7
fi
fi
fi
What is Java?
"Why have a separate compilation step?"

Compiled code is almost always much faster than "interpreted" code. At the
time, features like "Just-in-time" (JIT) compilation, faster garbage collection, and
various optimizations either didn't exist, or weren't good enough for consumer
use

Java's approach was to let programmers write in a high level language, compile
to an intermediate language (IL) and create interpreters (or JVMs) for this IL on
various hardware platforms

This way, you compile your source code once, and can run the program on
any* platform that has the JVM. Java calls this approach "write once, run
anywhere."

8
Java Editions
The JDK acronym zoo

• The tools for building Java programs are distributed as a Java Development Kit
(JDK), of which there are many "editions"

• Java Standard Edition (J2SE): The most common JDK for client-side standalone
applications, and what we use in this class

• Java Enterprise Edition (J2EE): Used for developing server-side applications,


servlets, and programs which work with other enterprise products provided by
Oracle (Sun)

• Java Micro Edition (J2ME): Used for developing applications for mobile devices such
as cell phones (pre-smartphone)

• JavaFX: an attempt to unify and modernize desktop and mobile (iOS/android)


9
Java Language Basics

10
Java Program Structure
Basics of syntax

• Java is a pure object-oriented language: everything is written within a class


block. To run a program, you give the JVM the name of a class, and the JVM
starts the program in that class' main method.

• What does a class block look like? (Things below in [ ]'s are optional)
[Class documentation]
[package statement]
[import statement(s)]
[interface statement(s)]
[class de nition(s)]
main method class de nition

11
fi
fi
Java Program Structure
Example
/* A simple Java program. These comments should be for documenting
what this class (program) does at a high level.
*/

/* an import statement */
import java.lang.*;

/* the name of this class is "Hello World" */


public class HelloWorld {

/* the main function is the code that runs when this class is
executed
*/
public static void main(String[] args){
/* prints the message "Hello World!" */
System.out.println("Hello World!");
}
} 12
Java Program Structure
Java program = Comments + Tokens + whitespace

• There are three styles of comments in Java:


• Single line comments, start with // and indicate the rest of the line is a comment:
System.out.println("Hello World!"); //say hello

• Multi-line comments, start with /* and end with */ and indicate anything in between is a
comment:

/* The prime numbers can be divided into two groups:


2 The only even prime
3,5,7… All other primes
*/

• Javadoc comments, start with /** and end with */ and indicate specially formatted comments
that can be used to automatically generate documentation with the javadoc tool. (Examples later)

13
Java Program Structure
De ning terms: tokens

There are ve types of tokens in Java:

• Reserved words / keywords: things that have special meaning to the compiler (if, for,
class)

• Identi ers: names a programmer gives to things (variables, classes, packages)


• Literals: actual hard-coded data (-1, true, "hello")
• Operators: symbols representing (usually) math operations (+, -, >=)
• Separators: symbols for grouping or separating other pieces of code
( (), {}, ;)

We'll go through each type next

14
fi
fi
fi
Reserved words / keywords
tokens:keywords

Keywords have special meaning to the compiler. They can never be used as
identi ers. Some are not currently used, but are reserved for future use
(const, goto)
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void volatile while enum
15
fi
Identifiers
tokens:identi ers
The "proper nouns" of programming
Identi ers are programmer chosen names used for classes, methods, variables, objects,
packages…

There are a few rules about what can be a valid identi er:

• Must begin with (one of)


• Letter, Underscore character ( _ ) or any currency symbol ($)
• Remaining characters can be
• Any of the above, and also numeric digits (0, 1, 2…)
• There is no limit to how long an identi er can be
• Java is case sensitive (foo is not Foo is not FOO is not…)
16
fi
fi
fi
fi
Identifiers
tokens:identi ers
Conventions
While not rules, the following are naming conventions (good ideas, not requirements)
used widely used by many Java developers:

• Class names start with upper case letters, and should be inter-cap (StudentGrade)
• Variable names start with lower case letters, and should be inter-cap
(assignmentList)

• Method names start with lower case letters, and should be inter-cap
(calculateTotal)

• Names of constants are often written in all caps, replacing spaces with underscores
(MAX_PRICE)

17
fi
Literals
tokens:literals

Literals are how a programmer represents explicit data values in a program.

These values can be:

• Assigned to variables ( greetMsg = "Hello!" )


• Passed to methods ( setVisible(false) )
• Used as part of a larger computation/expression ( 2*sin(3.1415/4) )
An expression can contain literals, operators, and other expressions*!

18
Operators
tokens:operators

An operator is a token (usually a symbol, but not always!) that takes one or more
arguments, called operands, and…operates on them to produce a result

There are 5 types of operators:

• Arithmetic operators
• Assignment operators
• Increment/decrement operators
• Relational operators
• Logical operators
19
Arithmetic operators
Tokens:operators:arithmetic

Arithmetic operators commonly work with numerical values (think calculator buttons).
They include
Order of operations:
• Multiplication *
1. Parentheses
• Division /
2. Multiplication, Division,
• Addition + and Mod (from left to right)
• Subtraction -
3. Addition and Subtraction
• Modulus % (the remainder of dividing the LHS by the RHS) (left to right)
Arithmetic operators can be unary (one operand), binary (two), or ternary (three)

20
Assignment Operators
tokens:operators:assignment

op1 = op2

Assigns the value of op2 (usually an expression) to op1 (always a variable). In addition
to the simple assignment operator, there are also compound assignment operators
that are shortcuts for common operations
op1 += op2

is equivalent to
op1 = op1 + op2

Compound assignment operators exist for all the arithmetic operations plus a few
more
21
Increment/Decrement operators
tokens:operators:increment/decrement

"Increase the value of this variable by 1" is such a common operation that it has
its own operator: ++op

However, there is some subtlety here! Since ++op is an expression (it evaluates
to a value), what should it evaluate to? Two options: the value of op after being
incremented (++op) OR the value of op before it was incremented (op++). This
will be particularly useful when we work with loops and arrays.

The above are called pre x (++op) and post x (opp++) increment operators.
Decrement operators also exist (--op and op--), and just reduce the value
by 1 rather than increasing

22
fi
fi
Relational Operators (comparison operators)
tokens:operators:relational

Relational or comparison operators are binary operators that take two


operands and return true or false, based on some comparison. Examples:
(36%2)== 0; //evaluates to true
(27/5) - 5 > 0; //evaluates to false

NOTE! NOT
the same as
ASSIGNMENT!

23
Order of operations:
Logical Operators 1. Negation (!)
tokens:operators:logical 2. Logical AND (&&)

3. Logical OR (||)
All the ways of gluing binary (true or false) values together
Example
Operator Returns true if "Short circuits"?
expression
&& op1 && op2 Both op1 and op2 are true Yes, rst false operand

|| op1 || op2 Either op1 or op2 is true Yes, rst true operand

! !op op is false No

& op1 & op2 Bitwise AND operation No

| op1 | op2 Bitwise OR operation No

^ op1 ^op2 Bitwise XOR operation No

24
fi
fi
Short-circuit evaluation
tokens:operators:logical

Consider the following expression


( a > 2.0 && (sqrt(a) - sin(a)) < (floor(a)*log(a)) )

The rst part of the expression is much simpler to compute than the second part. If the rst part is
false, the overall expression will be false, and we can save time by not computing the second
part. Java evaluates && and || from left to right, stopping (short-circuiting) when the result is found.

However, when Java short-circuits an expression, sometimes the implications aren't so obvious.
Consider this expression:
( b < 5 || (++b / 2) > 10 )

What happens when b is greater than 5? What happens when b is less than 5? What will be the
value of b after this expression?

25
fi
fi
Operator Precedence
"Order of operations" when mixing di erent kinds of operators

A single expression can mix all of the di erent kinds of operators together. It is
best practice to use parentheses whenever things might get confusing, but Java
does have a set precedence among the di erent operators:

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

26
ff
ff
ff
Separators
tokens:separators
Name Symbol

Usage: Parentheses ()
• Grouping operations together Braces {}
• Changing the default order-of-operations
Brackets []
• Ending / separating distinct computations
Semicolon ;
• "Accessing data and methods"**
Comma ,
Period .

27
Variables and Data Types

28
Variables
Declaring variables

Variables are named memory locations that can be assigned a value. The "name" of the
variable is an identi er. Useful for storing partial results for large/complex computations, or
for storing "state" within an object**.

Syntax for declaring a variable:

• Data type - describes what kind of values the variable can hold (REQUIRED)
• Variable name - unique identi er for this memory location (REQUIRED)
• Comment - describes the purpose, limits, and use of the variable (optional)

29
fi
fi
Variables
Initializing variables

Creating a variable in Java is a two-step process. Declaration tells Java "the


following identi er can be used to hold data of this type." Initialization gives a
variable an initial value. Java allows you to do both with a single line.

30
fi
Variables
Three di erent kinds of variables

There are three di erent kinds of variables in Java

• Instance variables** - hold data for an instance of a class


• Class variables** - hold data shared among all instances of a class
• Local variables - hold data within a method or other block.
Local variables behave similarly in many programming languages. We will return
to the other kinds of variables later on in the course.

31
ff
ff
Data types
Keyword Description Size/format
Unlike some other languages Integral numbers
(Python), Java requires the byte Byte-length integer 8-bit two's complement
programmer to give the type of data short Short integer 16-bit two's complement
a variable can hold explicitly. The
int Integer 32-bit two's complement
reason for this is that it makes for
Long integer 64-bit two's complement
much much faster code. long
Real numbers
Data types in Java can be split into float Single precision oating point 32-bit IEEE 754
two kinds: primitive types and double Double precision oating point 64-bit IEEE 754
reference types**. Each data type is Other types
stored in memory with a speci c
char 16-bit Unicode character
format.
boolean true or false

32
fl
fl
fi
Data type literals
Di erent data types have di erent literal formats (so Java knows how to
interpret literal values in your code)

• Integer: numbers without a decimal • Float: ends with the character 'f'
point float foo = 123.45f;
int foo = 12345;
• Long: ends with the character 'L'
• Double: numbers with a decimal long foo = 12345L;
point
double foo = 123.45; • Character: a single letter in single
quotes
char foo = 'a';
33
ff
ff
Data types
Notes

• The boolean type has a value of true or false (there is no conversion


between boolean and other types).

• All integral types in Java are signed (can be positive or negative).


• Reference types:
• Arrays, classes, and interfaces are reference types
• The value of a reference type variable, in contrast to that of a primitive type,
is a reference to (memory address of) the value or set of values represented
by the variable (so we need to watch out for aliasing for reference types).

34
Default values

In Java, a variable can never be uninitialized. If no explicit initial value is given,


Java sets the variable to a default based on it's type

Variable type Default initialization

byte, short, int, long 0

float, double 0.0

char '\u0000'

boolean false

All reference types null

35
Expressions
Terminology

• Combine literals, variables, and operators to form expressions


• Expressions are segments of code that perform computations when evaluated
• Expressions can contain:
• Literals (3.14)
• Variables (myCounter)
• Method calls (sqrt(25))
• An operator acting on one or more other expressions
binary operator: phase + sin(90)
unary operator: -discount

• Other expressions in parentheses: (3.14-amplitude)

36
Statements
Terminology

Roughly equivalent to sentences in natural We've already seen declaration statements,


languages, a statement forms a "complete and we'll return to control ow statements.
unit of execution" and is usually ended with Expression statements can be broken into
a semicolon (;). ve categories:

There are three kinds of statements in Java • Null statements (weird but necessary)
• Expression statements (computing things) • Assignment operations
• Declaration statements (creating/naming • Any use of ++ or --
things)
• Method calls
• Control ow statements (deciding where
to go next) • Object creation expressions**

37
fi
fl
fl
Statements
Examples
double aValue; //declaration statement;
aValue = 8933.234; //assignment statement
aValue++; //increment statement
System.out.println(aValue); //method call statement
Integer integerObject = new Integer(4); //object creation statement

• A control ow statement regulates the order in which statements get


executed.

• For example: if, for, while, return, break (and more)

38
fl
Scope and Lifetime of variables

• The scope of a variable is the region of a program within which the variable
can be referred to by its simple name.

• Scope also determines when the system allocates and clears memory for the
variable

• A block de nes a scope. Each time you create a block of code, you are
creating a new, possibly nested scope.

• Objects declared in the outer block will be visible to code within the inner
block, from the declaration down. (The reverse is not true)

39
fi
Scope and Lifetime of variables
Continued

• Variables are accessible when their scope is rst entered, and inaccessible
after their scope is left*. A variable that has "gone out of scope" will not retain
the value it previously stored.

• The lifetime of a variable is con ned to its scope. For most local variables,
this means the enclosing block of code.

• You cannot declare a local variable in an inner block to have the same name
(identi er) as a variable declared in an enclosing block. You can do this with
class/instance variables (called variable shadowing), which can lead to some
very di cult to debug problems!

40
fi
ffi
fi
fi
Blocks
Terminology

A block is a group of zero or more statements between balanced braces ({}).


For example, block 1 and block 2:
if (Character.isUpperCase(aChar)){
System.out.println("The character " + aChar + " is upper case.");
} else {
System.out.println("The character " + aChar + " is lower case.");
}

41
Type conversion

Evaluating an expression can result in implicit conversion of values in the


expression.

• Integer arithmetic yields results of type int unless at least one of the operands is
of type long

• Floating-point arithmetic yields results of type double if at least one of the


operands is of type double

Conversion of a narrower data type to a broader data type is (usually) done without
loss of information, while conversion the other way round may cause loss of
information. The compiler will issue an error message if a conversion will result in
information loss, or if the types cannot be converted.
42
Type conversion
Examples
int i = 10;
double d = 3.14;
d = i; //OK! d will be 10.0 after conversion
i = d; //Not OK without an explicit cast, data will be lost
i = (int)d; //Accepted by compiler because of explicit cast
Explicit type casting syntax:
(<cast-to-type>)<variable or literal value>
float f = 3.5f; //types match
int x = (int)2.7; //explicit cast
f = (float)2.9; //explicit cast
float y = 98; //narrow (int) to broad (float)
byte b = (byte)2; //explicit cast
float z = y+b; //narrow to broad (98.0f + (byte)2) becomes (98.0f+2.0f)
b = (byte)z; //explicit cast
43
Control Flow

44
Control flow
(Also called " ow control")

• if statements

if (condition) {
//do something
}

(The condition is a boolean expression that must be in parentheses)

45
fl
Control flow
if statement examples
if ((x>1) && (a+b == c)) {
System.out.println(a+b);
}
/* Note the conditional expression short-circuit: if (x>1) is false, then
Java knows it doesn't need to check (a+b == c). */
if(x>=0){
System.out.println(x);
} else {
System.out.println(-x);
}
if(x<1){
System.out.println("x is too small");
} else if(x>5){
System.out.println("x is too large");
}
46
Control flow
switch statement
if(x == 0){ switch(x) {
System.out.println("zero"); case 0:
} else if(x==1){ System.out.println("zero");
System.out.println("one"); break;
} else if(x==2){ case 1:
System.out.println("two"); System.out.println("one");
} else if(x==3){ break;
System.out.println("three"); case 2:
} else { System.out.println("two");
System.out.println("zero"); break;
} case 3:
System.out.println("three");
break;
default:
System.out.println("many");
}
47
While loops
// a while loop will continue "as long as" the condition is true
int x = 0;
while (x<5){
x++;
System.out.println(x);
}

// a do-while loop executes once before checking the condition


int x = 0;
do {
x++;
System.out.println(x);
} while (x<5);
//when would you use this form instead?

48
For loops
Syntax

for (initializer; condition; update){


//do something
}
//Example: print out the numbers 0 through…
for (int i=0; i<5; i++){
System.out.println(i);
}

49
For loops
Compared to while loops
for (initializer; condition; update){
//do something
}
// same as:
initializer;
while(condition){
//do something
update;
}
50
For loops
Compared with Python

//Java
for (int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}

#Python
for i in range(len(L)):
print(L[I])

51
For-each style loops

//for each element x in L


for (int x : L){
System.out.println(x);
}
What is L? What kinds of data types are acceptable for L? How would Java
(compiler? JVM?) check? When would you use for-each vs "old style" for?

52
Additional control flow statements

There are other ways to exit a loop without waiting for the condition to be false:

• break
Breaks out of the current loop altogether, and resumes executing after the end of
the loop

• continue
Breaks out of the current iteration of the loop, but continues on the next iteration
(skips any code after this statement within the loop block)

• return
Returns from the current method call immediately, and as a side-e ect breaks
out of any currently executing loop
53

ff

You might also like