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

Lecture02-Java Class Basics

Uploaded by

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

Lecture02-Java Class Basics

Uploaded by

Ramsha Imran
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

INTRODUCTION

TO JAVA
Java Basics
Key Words
■ Key words in the sample program are:
– public
– class
– static
– void
– String
■ String is not really a key word but is the name of a
predefined class in Java
■ We’ll go over the difference between these later
■ Key words
– lower case (Java is a case sensitive language).
– cannot be used as a programmer-defined identifier.

3
The Java Keywords

abstract continue goto package


synchronized assert default if
private this boolean do
implements protected throw break
double import public throws
byte else instanceof return
transient case extends int
short try catch final
interface static void char
finally long strictfp volatile
class float native super
while const for new
switch
Programming
Languages
■ Some Java key words have no meaning but are
reserved to prevent their use. (ex. goto, const,
include)
■ Semi-colons are used to end Java statements;
however, not all lines of a Java program end a
statement.
■ Part of learning Java is to learn where to properly
use the punctuation.

5
Lines vs Statements

■ There is a difference between lines and statements


when discussing source code.
System.out.println(
message);
■ This is one Java statement written using two lines.
Do you see the difference?
■ A statement is a complete Java instruction that
causes the computer to perform an action.

6
Capitalization

■ Case matters!

■ public ≠ Public ≠ PUBLIC


– This is different than FORTRAN and BASIC
– This is the same as C/C++

■ You can use Public as a identifier


– Not recommended, though!

7
Identifiers
• Identifiers are used for
• class names,
• method names,
• variable names.

• An identifier may be any descriptive sequence of


• uppercase and lowercase letters,
• numbers,
• the underscore
• dollar-sign characters.

• They must not begin


• with a number,

• Java is case-sensitive
• VALUE is a different identifier than Value.
Identifiers
Valid identifiers are:
■AvgTemp , count , a4 ,$test , this_is_ok

Invalid variable names include:


■2count , high-temp, Not/ok

 Good identifiers will help the graders


understand your program!
Identifiers
 Good ones are compact, but indicate
what they stand for
 radius, width, height, length

 Bad ones are either too long


 theRadiusOfTheCircle
 theWidthOfTheBoxThatIsBeingUsed
 the_width_of_the_box_that_is_being_used
 Or too short
 a, b, c, d, e
Literals

■ A constant value in Java is created by using a literal


representation of it. For example,
■ here are some literals:

■ 100 98.6 ‘X’ “This is a test”


Separators

■ () Parentheses
– Used to contain lists of parameters in method
definition and invocation. Also used for defining
precedence in expressions, containing
expressions in control statements, and
surrounding cast types.
■ {} Braces
– Used to contain the values of automatically
– initialized arrays. Also used to define a block of
code, for classes, methods, and local scopes.
■ [] Brackets
– Used to declare array types. Also used when
dereferencing array values.
Separators

• ; Semicolon
– Terminates statements.
• , Comma
– Separates consecutive identifiers in a variable
declaration.
– Also used to chain statements together inside a fo
statement.
• . Period
– Used to separate package names from subpackage
and classes. Also used to separate a variable or
Escape Sequence Description

\ddd Octal character (ddd)


\uxxxx Hexadecimal UNICODE character (xxxx)
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New line (also known as line feed)
\f Form feed
\t Tab
\b Backspace

String Literals

Examples of string literals are

“Hello World”
“two\n lines”
“\”This is in quotes\””
Data Types

15
Primitive variable types
■ Java has 8 (or so) primitive types:
– float
real numbers
– double
– boolean two values: true and false
– char a single character
– byte
– short
integer numbers
– int
– long

 Also the void “type”, which we will see later


16
Primitive real (floating-
point) types
■ A float takes up 4 bytes of space
– Has 6 decimal places of accuracy: 3.14159

■ A double takes up 8 bytes of space


– Has 15 decimal places of accuracy:
3.14159265358979

■ Always use doubles


– It will save you quite a headache!

17
Primitive integer types

■ Consider a byte:

0 1 0 0 0 1 0 1

 1 byte = 8 bits
 Each bit has two possibilities: 0 or 1

 28 = 256
 Thus, a byte can have any one of 256 values

 C/C++ has unsigned versions; Java does not

18
Primitive integer types

Type Bytes Minimum value Maximum value

byte 1 -27=-128 27-1=127

short 2 -215= 215-1=


-32,768 32,767

int 4 -231=-2,147,483,648 231-1=2,147,483,647

long 8 -263=-9,223,372,036, 263-1=9,223,372,036,


854,775,808 854,775,807

19
Primitive character type

■ All characters have a integer equivalent


– ‘0’ = 48
– ‘1’ = 49
– ‘A’ = 65
– ‘a’ = 97

■ Thus, you can refer to ‘B’ as ‘A’+1

20
Primitive boolean type
■ The boolean type has only two values:
– true
– false

21
Java operators
■ The following are the common operators for ints:
– +-/*%
– Division is integer division
■ 6 / 2 yields 3
■ 7 / 2 yields 3, not 3.5
■ Because everything is an int, the answer is an int
– Modulus is %
■ Returns the remainder
■ 7 % 2 yields 1
■ 6 % 2 yields 0

■ Floats and doubles use the same first four operators


– +-/*
– 7.0 / 2.0 yields 3.5
– 7.0 / 2 yields 3.5
– 7 / 2.0 yields 3.5
– 7 / 2 yields 3

22
Java operators
■ Booleans have their own operators
– && is AND
■ Only true when both operands are true
■ true && true yields true
■ false && true yields false
– || is OR
■ True when either of the operands (or both) are true
■ true || false yields true
■ false || false yields false
– ! is NOT
■ Changes the value
■ !true yields false
■ !false yields true

23
Variables
Defining variables
■ We’ve seen variables before in math
– y = mx + b
– Here y, m, x, and b can hold any value
■ To store things in a computer program, we also use
variables
■ Example:
– int x = 5;
– Visualization:
– This defines an integer variable with value 5 x 5

■ The variable is x
■ The type is int

25
Basic Variable Declaration
Basic form of variable declaration:
More on variables

■ An integer variable can only hold integers


– In other words, it can’t hold 4.3
■ To hold floating point values, we use the double
type
– double d = 4.3; d 4.3

■ The variable is d
■ The type is double

27
Primitive variable
assignment
■ Assignment operator =
– Allows the memory location for a variable to be
updated
 Assignment operator =
 Allows the variable to be updated

– Consider
int j = 11;

j 1985
11
 Consider
int j = 11;
j = 1985;

28
Primitive variable
assignment
 Consider
a 1
5
int a = 1;
int aSquared = a * a; 25
1
a = 5; aSquare
aSquared = a * a; d

 Consider
i 0
1
int i = 0;
i = i + 1;

 Consider
int asaRating; asaRati 400
-
asaRating = 400; ng
29
Primitive variable
assignment
 Consider
double x = 5.12; x 19.28
5.12
double y = 19.28;
double rememberX = x;
y 19.28
5.12
x = y;
y = rememberX;
rememberX 5.12

30
Printing variables

■ To print a variable to the screen, put it in a


System.out.println() statement:

– int x = 5;
– System.out.println (“The value of x is “ + x);

■ Important points:
– Strings are enclosed in double quotes
– If there are multiple parts to be printed, they
are separated by a plus sign

31
public class SolvingABC {

public static void main(String[] args) {

// variable definitions and initializations


int a = 3;
int b = 12;
int c = 6;
int d = 1;

// calculate results
double result1 = d * a;
Note that I don’t double result2 = c + 2 * a;
show a lot of double result3 = d - b / c;
comments so that double result4 = c * b % c;
double result5 = b / 2;
the code will fit on
a single slide // display the results
System.out.println();
Also note all the System.out.println("result1 : " + result1);
semi-colons System.out.println("result2 : " + result2);
System.out.println("result3 : " + result3);
System.out.println("result4 : " + result4);
System.out.println("result5 : " + result5);
System.out.println();

}
}
Variable initialization

■ Note that the following

– int x;
– x = 5;

■ is (mostly) the same as the following:

– int x = 5;

33
You can only declare
variables once
■ The following code will not work:

– int x = 5;
– int x = 6;

■ Java can have only one variable named x


– So you can’t declare multiple variables with the
same name
– (we’ll see ways around this later in the
semester)

34
Let’s Practice

■ The content of this lecture is taken from different


sources like oracle, MIT lectures, quora.com and
others
Compute the light travel distance
class Light {
public static void main(String args[]) {
int lightspeed = 186000;
long days = = 1000;
long seconds = days * 24 * 60 * 60;
long distance = lightspeed * seconds;
System.out.print("In " + days);
System.out.print(" light will travel about
");
System.out.println(distance + " miles.");
}
}
Program outline for
BMI.java
// Purpose: Compute BMI for given weight and height

public class BMI {

// main(): application entry point


public static void main(String[] args) {
// define kilo_per_Pound and Meter_per_Foot

// set up person's height in feet and weight in pounds

// convert to metric equivalents

// perform bmi calculation using formula


//bmi=weightinkilo /heightinMeter * heightinMeter

// display result
}
} 37

You might also like