0% found this document useful (0 votes)
34 views69 pages

Java Basics: Identifiers, Variables, and Types

This document provides a summary of a lesson on basic Java elements including program elements, identifiers, variables, data types, and expressions. The lesson contains slides that: 1) Show a simple "Hello World" Java program and discuss program structure and the main method. 2) Explain Java identifier syntax and semantics, including naming conventions and case sensitivity. 3) Demonstrate variable declaration and initialization with examples. 4) Describe Java's primitive data types including integers, floating-point, characters, and booleans. 5) Introduce assignment statements and arithmetic operators in expressions.

Uploaded by

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

Java Basics: Identifiers, Variables, and Types

This document provides a summary of a lesson on basic Java elements including program elements, identifiers, variables, data types, and expressions. The lesson contains slides that: 1) Show a simple "Hello World" Java program and discuss program structure and the main method. 2) Explain Java identifier syntax and semantics, including naming conventions and case sensitivity. 3) Demonstrate variable declaration and initialization with examples. 4) Describe Java's primitive data types including integers, floating-point, characters, and booleans. 5) Introduce assignment statements and arithmetic operators in expressions.

Uploaded by

Mohammed Msallam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Lesson B - Basic Java Elements

Unit B1 – Program Elements

Lecture B Slide 1 of 6
Hello World Program, Again

// My First Program!!
public class HelloWorld {
public static void main(String[] args){
System.out.println(“Hello World!”);
}
}

Lecture B Slide 2 of 6
Identifiers: Syntax
• Identifiers are the words a programmer uses in a program
• Identifier syntactic rules:
 Can be made up of any length of
• letters
• digits
• underscore character (_)
• dollar sign ($)
 Cannot begin with a digit
• Java is case sensitive
 User and user are completely different identifiers

Lecture B Slide 3 of 6
Identifiers: Semantics
• Identifiers names can come from the following sources
 Fixed in Java as reserved words
• public, class, static, void, method, …
 Chosen by the programmer to denote something
• HelloWorld, main, args
 Chosen by a programmer whose code we use:
• String, System, out, println

Lecture B Slide 4 of 6
Naming style
• The correctness of the program is not affected by the
names used
public class X7_65Tx { … }
• Names play a central role in the readability of the program
• They are part of its documentation
• They should thus be chosen carefully
 BankAccount, size, numberOfElements
• Follow conventions in choosing names!

Lecture B Slide 5 of 6
White Space
• Spaces, blank lines, and tabs are collectively called white
space
• White space is used to separate words and symbols in a
program
• Extra white space is ignored
• A valid Java program can be formatted many different
ways
• Programs should be formatted to enhance readability,
using consistent indentation

Lecture B Slide 6 of 6
Valid, but bad Indentation

public class
HelloWorld { public static void

main(String[]
args) {
System.out.println(“Hello World!”)
;}}

Lecture B Slide 7 of 6
Comments
• Comments are ignored and are treated as white space
• They should be written to enhance readability
 Explain what a piece of code does (its interface)
 Explain any special tricks, limitations, …
• Java has three comment formats:
 // comment to end of line
 /* comment until
closing */
 /** API specification comment */

Lecture B Slide 8 of 6
Lesson 2 - Basic Java Elements
Unit B2 - Variables and Data Types

Lecture B Slide 9 of 6
Variables
• A variable is a location in memory that can hold values of
a certain data type
• Each variable must be declared before it is used
• The declaration allocates a location in memory to hold
values of this type
• Variable types can be
 primitive
 reference to an object

Lecture B Slide 10 of 6
VariableExample Program

public class VariableExample {


public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

Lecture B Slide 11 of 6
VariableExample Program (2)

public class VariableExample {


public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

x
Lecture B Slide 12 of 6
VariableExample Program (3)

public class VariableExample {


public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

x
Lecture B Slide 13 of 6
VariableExample Program (4)

public class VariableExample {


public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

3
x
Lecture B Slide 14 of 6
VariableExample Program (5)

public class VariableExample {


public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

4
x
Lecture B Slide 15 of 6
VariableExample Program (6)

public class VariableExample {


public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}

4
x
Lecture B Slide 16 of 6
Primitive Data Types
• A data type is defined by a set of values and the
operators you can perform on them
• The Java language has several predefined types, called
primitive data types
• The following reserved words represent the eight different
primitive data types:
 byte, short, int, long, float, double, boolean,
char

Lecture B Slide 17 of 6
Integers
• There are four integer data types. They differ by the
amount of memory used to store them

Value Range Bits Type


-127 … 128 8 byte

-32768 … 32767 16 short

about 9 decimal digits 32 int

about 18 decimal digits 65 long

Lecture B Slide 18 of 6
Floating Point
• There are two floating point types

Precision Range Bits Type


(decimal digits) (decimal digits)
7 38 32 float

15 308 64 double

Lecture B Slide 19 of 6
Characters
• A char value stores a single character from the Unicode
character set
• A character set is an ordered list of characters
 ‘A’, ‘B’, ‘C’, … , ‘a’, ‘b’, … ,‘0’, ‘1’, … , ‘$’, …
• The Unicode character set uses 16 bits per character,
allowing for 65,536 unique characters
• It is an international character set, containing symbols and
characters from many world languages
• The ASCII character set is a subset of Unicode
• ASCII is the current standard (outside of Java)

Lecture B Slide 20 of 6
Boolean
• A boolean value represents a true/false condition.
• It can also be used to represent any two states, such as a
light bulb being on or off
• The reserved words true and false are the only valid
values for a boolean type

Lecture B Slide 21 of 6
Variable Declarations
• The syntax of a variable declaration is
data-type variable-name;
• For example
int total;
• Multiple variables can be declared on the same line
long total, count, sum;
• Variables can be initialized (given an initial value) in the
declaration
int total = 0, count = 20;
double unitPrice = 57.25;

Lecture B Slide 22 of 6
Variable Declaration Example

public class DeclarationExample {


public static void main (String[] args) {
int weeks = 14;
long numberOfStudents = 120;
double averageFinalGrade = 78.6;
System.out.println(weeks);
System.out.println(numberOfStudents);
System.out.println(averageFinalGrade);
}
}

Lecture B Slide 23 of 6
More Variable Examples

double pi, conversionRate, temprature;


long salary;
boolean isOn;
char c;

pi = 3.14159;
isOn = false;
c = ‘A’;
salary = 34000;
isOn = true;

Lecture B Slide 24 of 6
Constants
• We may declare that a variable is a constant and its value
may never change.
final double PI = 3.14159;
final int CHINA_OLYMPICS_YEAR = 2008;

• Advantages:
 readability
 efficiency
 error detection

Lecture B Slide 25 of 6
Lesson 2 - Basic Java Elements
Unit B3 - Expressions

Lecture B Slide 26 of 6
Assignment Statements
• An assignment statement takes the following form
variable-name = expression;
• The expression is first evaluated
• Then, the result is stored in the variable, overwriting the
value currently stored in the variable

Lecture B Slide 27 of 6
Arithmetic Operators
• An operator is a mapping that maps one or more values
to a single value:
• Binary Operators:
a + b adds a and b
a - b subtracts b from a
a * b multiplies a and b
a / b divides a by b
a % b the reminder of divining a by b
• Unary Operator:
-a The negation of a

Lecture B Slide 28 of 6
Pounds to Kg conversion

public class PoundsToKg {


public static void main(String[] args){
double weightInPounds = 200.0;
final double KILOS_IN_POUND = 0.455;
double weightInKg;

weightInKg = weightInPounds * KILOS_IN_POUND ;


System.out.println(weightInKg);
}
}

Lecture B Slide 29 of 6
Pounds to Kg conversion 2

public class PoundsToKg2 {


public static void main(String[] args){
final double KILOS_IN_POUND = 0.455;
System.out.println(200.0 * KILOS_IN_POUND);
}
}

Lecture B Slide 30 of 6
Integer Division
• When division is performed on integers (byte, short,
int, long), the result is truncated to an integer.

int j = 5;
double x = 5.0, y;
System.out.println(j / 2); // 2
System.out.println(x / 2.0); // 2.5
System.out.println(5 / 2); // 2
y = j / 2 ; // 2

Lecture B Slide 31 of 6
Complex Expressions
• Expressions can combine many operators and operands
• Examples:
x
-34
weight * 2.73
2 * PI * r
a - (7 – b)
1 + 2 + 3 + 4
(x + y) * (2 - z + (5 - q)) * -(1-x)

Lecture B Slide 32 of 6
Operator Precedence
• Multiplication, division, and remainder (%) have a higher
precedence than addition and subtraction.
• Operators with same precedence evaluate from left to
right.
• Parenthesis can be used to force order of evaluation.

Lecture B Slide 33 of 6
Operator Precedence Examples

Result Expression
2 10 - 7 - 1

4 10 - (7 - 1)

7 1 + 2 * 3

9 (1 + 2) * 3

15 1 - 2 * 3 + 4 * 5

Lecture B Slide 34 of 6
Conversions
• Data types can be mixed in an expression
• When the expression is evaluated one type is converted to
another
• Data is converted to a wider type in three cases
 assignment conversion
 arithmetic promotion
 casting
• Can be converted to a narrower type only by casting
• List of types from narrowest to widest:
Narrow … Wide
byte short int long float double

Lecture B Slide 35 of 6
Conversion Examples

double f, x;
int j;
f = 5;
f = 5.0 / 2;
f = x * j;
f = 5 / 2;
f = (float) j / 5;
j = (int) f;
j = (int) 5.0 / 2.0;

Lecture B Slide 36 of 6
Lesson 2 - Basic Java Elements
Unit B4 - Objects and Method Invocation

Lecture B Slide 37 of 6
Reference Types
• Variables can be declared to be of an object type. In this
case they hold a reference to an object of this type (class).
Turtle t;
String myName;
Date today;

t myName today

Memory

Lecture B Slide 38 of 6
Creating Objects
• Objects are created by invoking a constructor of the class.
Constructors may accept parameters.

Date today;
today = new Date(12345);// mSec since 1.1.1970
Turtle t = new Turtle();

Lecture B Slide 39 of 6
Creating Objects (2)
• Objects are created by invoking a constructor of the class.
Constructors may accept parameters.

Date today;
today = new Date(12345);// mSec since 1.1.1970
Turtle t = new Turtle();

today

Lecture B Slide 40 of 6
Creating Objects (3)
• Objects are created by invoking a constructor of the class.
Constructors may accept parameters.

Date today;
today = new Date(12345);// mSec since 1.1.1970
Turtle t = new Turtle();

today

12345

Lecture B Slide 41 of 6
Creating Objects (4)
• Objects are created by invoking a constructor of the class.
Constructors may accept parameters.

Date today;
today = new Date(12345);// mSec since 1.1.1970
Turtle t = new Turtle();

t today

12345

Lecture B Slide 42 of 6
Strings
Strings are objects that are treated by the compiler in special
ways:
 Can be created directly using “xxxx”
 Can be concatenated using +

String myName = “John Jones”;


String hello;
hello = “Hello World”;
hello = hello + “!!!!”;
int year = 2008;
String s = “See you in China in “ + year;

Lecture B Slide 43 of 6
Method invocations
• You may invoke methods on an object. Methods may
receive parameters.
• Methods may also return values.

Turtle leonardo = new Turtle();


leoardo.moveForward(100);
String lennon = “John Lennon”;
int len = lennon.length();
char initial = lennon.charAt(5);

Lecture B Slide 44 of 6
APIs
• To use an object you only need to know its application
programmer interface (API).
• The API of an object class includes a description of:
 all available constructors and methods and what they do
 the parameters they take and the values that they return
• The API is usually given in a special format called
javadoc.

Lecture B Slide 45 of 6
Javadoc example

Lecture B Slide 46 of 6
Javadoc example (2)

Lecture B Slide 47 of 6
Class Libraries
• A class library is a collection of classes that we can use
when developing programs
• There is a standard class library that comes with every
Java environment.
• Class Libraries are organized into packages
 java.net, java.lang, java.io, ...
• To use classes from a package you must either
 Import the package
 import java.io.*;
File f = new File(“John”);
 Or, use a fully qualified class name
java.io.File f = new java.io.File (“John”);

Lecture B Slide 48 of 6
RandomNumbers.java

import java.util.Random;
public class RandomNumbers {
public static void main (String[] args){
Random generator = new Random();
int num = generator.nextInt();
System.out.println ("A random int: " + num);
num = generator.nextInt();
System.out.print(“Another one: “ + num);
}
}

Lecture B Slide 49 of 6
Lesson 2 - Basic Java Elements
Unit B5 - Input and Output

Lecture B Slide 50 of 6
Types of Input and Output (I/O)
• Terminal-based I/O
 System.out.println()
 System.in.xxxxx()
• Graphic User Interface
 Windows, Buttons, Mouse, …
• Stream based I/O
 Files, Web, Communication, Terminal-based I/O
• In this course we also provide our own classes:
 InputRequestor, OutputWindow

Lecture B Slide 51 of 6
The InputRequestor Class
• To use the input requestor, you must first create the
object:

InputRequestor inp = new InputRequestor();

• Then, you may use it to read primitive data types:

int i = inp.requestInt();
int i = inp.requestInt(“Enter age:”);
float f = inp.requestFloat();

Lecture B Slide 52 of 6
InputRequestor Behaviour
• A window will pop up every time you use the
requestXXX() method:

• The window will disappear only after you have typed a


legal input. The method returns this input.

Lecture B Slide 53 of 6
The OutputWindow Class
• Just as System.out enables you to display output in the
MS-DOS window, you may display output in your own
window.
• Create an OutputWindow object:

OutputWindow outwin = new OutputWindow();

• Useful methods in the output window:


 println() - just as regular println().
 clear() - clears the output window.
 showMessage() - pop up a message on the desktop.

Lecture B Slide 54 of 6
The Output Window

Lecture B Slide 55 of 6
The showMessage() Pop-up Window

Lecture B Slide 56 of 6
Circle Area and Circumference

public class CircleCalc {


public static void main(String[] args){
final double PI = 3.14159;
InputRequestor in = new InputRequestor();
OutputWindow out = new OutputWindow();
double r = in.requestDouble("Radius: ");
out.println("Radius = " + r);
out.println("Area = " + PI * PI * r);
out.println("Circumference = " + 2 * PI * r);
}
}

Lecture B Slide 57 of 6
Lesson 2 - Basic Java Elements
Unit B6 - Introduction to Applets and Graphics

Lecture B Slide 58 of 6
The Web

Lecture B Slide 59 of 6
My First HTML Example

<H3>My First HTML File</H3>

<p>
Hello World!!!
<p>
Here is a link to
<a href=“http://www.cnn.com”>CNN</a>!

Lecture B Slide 60 of 6
My First Web Page

Lecture B Slide 61 of 6
Running programs in a web page
• Java was invented so that running programs can be
embedded in web-pages
• Such Java programs are called Applets
• This had to solve some problems
 Platform independence
• browsers have a built-in Java byte-code interpreter
 Security
• the program runs in the browser in a sandbox

Lecture B Slide 62 of 6
A Web Page with an Embedded Applet

Lecture B Slide 63 of 6
Writing Applets
• An Applet does not have a main method.
• Instead, it has a set of methods that control the interaction
with the user.
• An Applet inherits this interface from the
java.applet.Applet class
• The paint method has to paint the screen
 It receives a Graphics object, and uses it to paint
 The Graphics class has various drawXXX() methods

Lecture B Slide 64 of 6
Smiley.java
import java.applet.Applet;
import java.awt.*;
public class Smiley extends Applet{
public void paint (Graphics page){
page.setColor(Color.yellow);
page.fillOval(50,50,300,300);
page.setColor(Color.black);
page.fillOval(125,125,50,50);
page.fillOval(225,125,50,50);
page.drawLine(150,275,250,275);
}
}

Lecture B Slide 65 of 6
Smiley.HTML

<H3>My Smiley Applet</H3>


<applet code=”Smiley.class" width=400 height=400>
</applet>
<p>
Above this text you should see Smiley!!

• The Smiley.class file should be placed in the same


directory with Smiley.HTML

Lecture B Slide 66 of 6
Smiley

Lecture B Slide 67 of 6
Graphics Coordinates

10 150 X

20

45

page.drawLine (10, 20, 150, 45);

Lecture B Slide 68 of 6
Drawing an Oval

175 X

20

80

Y 50

page.drawOval (175, 20, 50, 80);

Lecture B Slide 69 of 6

You might also like