Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

02 Java

The document provides an introduction to the Java programming language. It discusses topics like data types in Java, variable declaration, operators, and strings. It also covers concepts like primitive vs object data, and methods for strings like length. The document is presented as a lecture slideshow on Java for a course.

Uploaded by

divya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

02 Java

The document provides an introduction to the Java programming language. It discusses topics like data types in Java, variable declaration, operators, and strings. It also covers concepts like primitive vs object data, and methods for strings like length. The document is presented as a lecture slideshow on Java for a course.

Uploaded by

divya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to Java

15-121 Fall 2020


Margaret Reid-Miller
Academic Integrity
• You must do your own work.
• Discussion with other students is limited to
clarifying the assignments or at a high non-
code level (pictures).
• If you need help, ask the course staff or me
(see the Staff page for office hours).
• You should never look at another person’s
program nor allow another student to look
at your program (except recitation labs).

Fall 2020 15-121 (Reid-Miller) 2


What if I cheat on a assignment?
• Record a negative score on the assignment.
• Reduce your final semester letter grade.
• Prevent you from dropping, withdrawing, or
changing to pass/fail.
• Send letters to Student Affairs, your advisor,
various deans, etc.
• May result in long-term suspension.

Fall 2020 15-121 (Reid-Miller) 4


Life happens
So I give you some late days. How many late
days in total? 4
How many late days can you use for a single
assignment?
2
What is the penalty for turning an assignment
late when you run out of late days?

No credit, so always submit something on time

Fall 2020 15-121 (Reid-Miller) 5


Quizzes

• When is our first quiz?


Tomorrow
• How often do we have a quiz?
Every Thursday
• How many quizzes will be counted?
10 (1-2 will be dropped)
• Can your arrange to make up a quiz?
You can’t, but each is worth only 0.5%

Fall 2020 15-121 (Reid-Miller) 6


Java vs Python
• Program Translation:
• Java is compiled, Python is interpreted
• Java syntax:
• Uses braces {} to group statements (indentation
is not semantic, but recommended)
• Most statements end in semi-colons.
• Java programs:
• Often have several classes, each in a file with
same name.
• Java programs start with the method main.

15-121 (Reid-Miller) 7
There is no required textbook.

• I will post related readings, however, from a


free on-line text book Introduction to
Programming Using Java by David J. Eck that
you may find helpful for your understanding.

• You are welcome to use other books on data


structures using Java.

Fall 2020 15-121 (Reid-Miller) 8


Today
• Data types (primitive/reference)
• Basic Operators
• Variable declaration
• Strings

• Before next lecture, review and compare


syntax of LetterCounter1.java and
LetterCounter1.py

Fall 2020 15-121 (Reid-Miller) 9


Java requires that you declare the type
of each variable before it is used.
• You also need to declare the type of the expression
return from a method
Basic types:
boolean (true or false)
int (integer)
double (floating point decimal)
String (sequence of characters)

void return type of a method that returns no value

• Java checks that the types match when you compile.


Compiler error messages often indicate a type mismatch.
Fall 2020 15-121 (Reid-Miller) 10
Primitive Data Types
• Java has two categories of data:
• primitive data (e.g., number, character)
• object data (programmer created types)

• There are 8 primitive data types:


byte, short, int, long, float, double,
char, boolean

• Primitive data are only single values; they have no


special capabilities

• You cannot define new primitive data types.


Fall 2020 15-121 (Reid-Miller) 11
Common Basic Types

Type Description Example of Literals


integers (whole
int 42, 60634, -8, 0
numbers)

double real numbers 0.039, -10.2, 4.2E+72

char single characters 'a', 'B', '&', '6'

boolean logical values true, false

String List of characters "", "a", "ab6&"

Fall 2020 15-121 (Reid-Miller) 12


Mostly use int and double

Type Storage Range of Values

byte 8 bits -128 to 127

short 16 bits -32,768 to 32,727

int 32 bits -2,147,483,648 to 2,147,483,647

long 64 bits -9x1018 to 9x1018

float 32 bits ±10-45 to ±1038, 7 significant digits

double 64 bits ±10-324 to ±10308, 15 significant digits

Fall 2020 15-121 (Reid-Miller) 13


Recall
• What is 210 in base 10, approximately?
103
• 220 ?
1 million
• 230 ?
1 billion
• 232 ?
4 billion

Fall 2020 15-121 (Reid-Miller) 14


Note the limited range of int

Type Storage Range of Values

byte 8 bits -128 to 127

short 16 bits -32,768 to 32,727

int 32 bits -2 billion to 2 billion, approximately

long 64 bits -9x1018 to 9x1018

float 32 bits ±10-45 to ±1038, only 7 significant digits!

double 64 bits ±10-324 to ±10308, 15 significant digits

Fall 2020 15-121 (Reid-Miller) 15


Basic Operators

Type Description Operators

int integers +, -, *, /, %, ++, --

double real numbers +, -, *, /

char single characters +, - (int arithmetic)

relational ==, !=, <, >, <=, >=


boolean
logical ! , &&, ||

String Strings + (concatenation)

Fall 2020 15-121 (Reid-Miller) 16


Before you can use a variable,
you must declare its type.

• You can declare a variable only once in a


method.

• Examples:
int numDimes;
double length; camelCase is the
Java convention
char courseSection;
boolean done;
String lastName;

Fall 2020 15-121 (Reid-Miller) 17


Declaring Variables
• Declaring a variable instructs the compiler to set
aside a portion of memory large enough to hold data
of that type.
int count;
double length;

count length

• No value has be put in memory yet. That is, the


variable is undefined.

Fall 2020 15-121 (Reid-Miller) 18


Assignment Statements
• An assignment statement stores a value into a
variable's memory location:
<variable> = <expression>;
• The type of the variable and expression must match.
• The first assignment to a variable initializes it.

count = 3; count 3
length = 72.3 + 2.0; length 74.3

Fall 2020 15-121 (Reid-Miller) 19


Assignment statements shortcuts
int n;
n = 0; int n = 0;

n = n + 1; n += 1; n++;
n = n - 1; n -= 1; n--;

Other assignment operators:


*=, /=, %=

Fall 2020 15-121 (Reid-Miller) 20


Strings
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

• String is not a primitive type, but a class/type


• String variables store references to memory
addresses
• Strings are immutable! That is, you cannot change a
string, but you can assign a new string to a variable.
• A string cannot span more than one line:
"Not a valid WRONG!
String literal”

How do you include a newline or single quote in a string?


Fall 2020 15-121 (Reid-Miller) 21
As with Python, Java has escape
sequences
Escape sequence: a two-character sequence that
represent a single special character.

Sequence Meaning
\t tab character
\n newline character
\" double quote
\' single quote
\\ backslash character

System.out.println(
"What \"character\" is this \\? ");
Fall 2020 15-121 (Reid-Miller) 22
An object of type String is a
sequence of (unicode) characters.

• When we declare a variable of type String, it does


not create an object.
founder null
String founder;
• To create an object we use the new operator:
founder = new String("Carnegie");
initializes its state
• Strings have a shortcut way of creating them:
String founder2 = "Mellon";

Fall 2020 15-121 (Reid-Miller) 23


Object vs Primitive Data
• A primitive variable holds an actual value:

int count = 15121; count 15121

• An object variable holds a reference (address) to the


object.
String founder = new String("Carnegie");
a35f3cd
"Carnegie" object data
founder a35f3cd
length() object methods
reference: computer substring()
generated address …
A String object

Fall 2020 15-121 (Reid-Miller) 24


String Length
method header
int length()
• int indicates that the data type of the value the
method returns.
• Returns the number of characters in this string.

• Example:
String founder = "Carnegie";
int numChar = founder.length();
object dot operator method

Fall 2020 15-121 (Reid-Miller) 25


Getting a single character
char charAt(int index)
Returns the character at a specified index
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
C a r n e g i e M e l l o n
Example:
String school = "Carnegie Mellon";
char firstChar = school.charAt(0);

WARNING: You cannot assign a char to an object of type String


without first converting the char to a String object !
e.g., String initial = "" + firstChar;

Fall 2020 15-121 (Reid-Miller) 26


An example of
method overloading,
Substrings where the number of
parameters differs.

String substring(int startIndex, int endIndex)


String substring(int startIndex)
Returns a new string consisting of the substring starting at
startIndex (inclusive) and ending at endIndex (exclusive)
or, if one parameter, to the last character.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
C a r n e g i e M e l l o n

Example:
String school = "Carnegie Mellon";
String founder = school.substring(0, 8);
String founder2 = school.substring(9);
Fall 2020 15-121 (Reid-Miller) 27
Replacing Characters
String replace(char oldChar, char newChar)
Returns a new String object resulting from replacing
every occurrence of oldChar with newChar.
• The original String object is unchanged.
(Strings are immutable!)

Example:
String founder = "Carnegie";
System.out.println( OUTPUT:
CarnEgiE
founder.replace('e', 'E')); Carnegie
System.out.println(founder);
Fall 2020 15-121 (Reid-Miller) 28
Changing Case
String toUpperCase()
Returns a new String object with all letters
converted to uppercase.

String toLowerCase()
Returns a new String object with all letters
converted to lowercase.
Immutable: You
need to print or
Example: assign the result to
String founder = "Carnegie"; a variable!
String upper = founder.toUpperCase();
String lower = founder.toLowerCase();

Fall 2020 15-121 (Reid-Miller) 29


Equals
boolean equals(String str)
Returns true if str represents the same sequence of
characters as this string.

Example:
String founder = "Carnegie";
founder.equals(“Carnegie”); // returns true
founder.equals(“carnegie”); // returns false

Fall 2020 15-121 (Reid-Miller) 30


Testing For Equality
• For primitive values use == for equality testing.
• For objects, use the equals method for testing
equal contents.
• The argument must be the same type as the object on which
equals() is called.

• For example:
if (day == 1 && month.equals(“APRIL”)) {
System.out.println(“It’s April Fool’s Day”);
}

WARNING: Never use == with strings! The


results are unpredictable!
Fall 2020 15-121 (Reid-Miller) 31
Compare the lexicographical
order of two strings
int compareTo(String str)
Returns:
• value < 0 if this string is “less than” str
• value = 0 if they are equal
• value > 0 if this string is “greater than” str

Example:
“mellon”.compareTo(“carnegie”); // returns positive #
“Mellon”.compareTo(“mellon”); // returns negative #

Fall 2020 15-121 (Reid-Miller) 32

You might also like