0% found this document useful (0 votes)
8 views

02.1 - Learning The Java Language

Uploaded by

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

02.1 - Learning The Java Language

Uploaded by

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

Learning the Java Language

(http://docs.oracle.com/javase/tutorial/java/index.html)
Objectives
• Study some fundamentals of Java
languages: Data types, variables, arrays,
operators, logic constructs.
• Pass arguments to the main method
• Input/output variables
• Concept: Package.
Keywords and Identifiers
 Keywords: Almost of them are similar to
those in C language
 Naming Convention:

Letter Letters
$ Digits, $
_ _

• Java is a case-sensitive language


• Identifiers must be different to keywords
Primitive Data Types - Variables
Type Bytes Minimum Maximum
• A primitive is a
char 2 \u0000 \uFFFF
simple non-
object data byte 1 -27 27 - 1
type that short 2 -215 215 – 1
represents a int 4 -231 231 – 1
single value.
long 8 -263 263 - 1
Java’s
primitive data float 4
types are: double 8
boolean true/false

Type var [=Initial value] ;


Operators
Category Operators
(Descending Precedence)

Unary ++ -- + - ! ~ (type)
Arithmetic * / %
+ -
Shift << >> >>>
Comparison < <= > >= instanceof
== !=
Bitwise & ^ |
Short-circuit && || They are the same with
Conditional ?: those in C language
Assignment = op=
Using Operators Demonstration
Using Operators Demonstration
Use 2 bytes to store value
1:  0000 0000 0000 0001
1111 1111 1111 1110 ( 1-complement)
-1  1111 1111 1111 1111 ( 2-complement)
-1 <<1  1111 1111 1111 1110 (-2)

-1  1111 1111 1111 1111


-1 >>1  1111 1111 1111 1111

-1  1111 1111 1111 1111


3 0000 0000 0000 0011 -1 >>>1  0111 1111 1111 1111 (2147483647)
4 0000 0000 0000 0100
3|4  0000 0000 0000 0111 (7)
3 0000 0000 0000 0011
4 0000 0000 0000 0100
3&4  0000 0000 0000 0000 (0)
3 0000 0000 0000 0011
4 0000 0000 0000 0100
3^4  0000 0000 0000 0111 (7 ): XOR BIT
Literals and Value Variables
 Character: ‘a’ Value variable
 String: String S=“Hello”;
 Escape sequences: see the page
10
Stack
 Integral literals:
28, 0x1c, 0X1A ( default: int).
123l, 123L (long)
 Floating point:
1.234 (default: double) n 10
1.3f 1.3F
1.3E+21
int n=10;
1.3d 1.3D
Java Expressions
• Java is an expression-oriented language. A
simple expression in Java is either:
• A constant: 7, false
• A char - literal enclosed in single quotes: 'A', '3‘
• A String - literal enclosed in double quotes: "foo“
• The name of any properly declared variables: x
• Any two|one of the preceding types of
expression that are combined with one of the
Java binary operators: i++, x + 2, (x + 2)
One Dimensional Arrays (1)

• An array is a container object that holds a


fixed number of values of a single type.
• The length of an array is established when
the array is created.
• Each item in an array is called an element,
and each element is accessed by its
numerical index.
One Dimensional Arrays (2)

• Declaring a Variable to Refer to an Array


int[] anArray;
or float anArrayOfFloats[];
• Creating, Initializing, and Accessing an
Array
anArray = new int[10];
• Copying Arrays
• Use arraycopy method from System class.
One Dimensional Arrays (3)
int[] ar;
ar= new int[3];
3
ar[0]=1; ar[1]=2; ar[2]=3;
Heap 2
int a2[]; 10000 1

int[] a3 = {1,2,3,4,5};
int a4[] = {1,2,3,4,5};
Stack ar 10000

Array is a reference variable


int n=10;
Multiple Dimensional Arrays
10 2002

9 500
2001
92
500
8 91
200 200
7
100 4
6 8000

5 3
1000
8000 2
replacement 1000 m
1
100

int m[][]= { {1,2,3,4}, {91,92}, {2001,2002}};


int[] replacement = {5,6,7,8,9,10}; m[i][j]
m[1]= replacement; int[][] m; // declare a matrix
int r=10, c=5; // number of rows, columns
m= new int[r][c]; // memory allocate
Evaluating Expressions and
Operator Precedence
• The compiler generally evaluates such
expressions from the innermost to outermost
parentheses, left to right.
int x = 1; int y = 2; int z = 3;
int answer = ((8 * (y + z)) + y) * x;
would be evaluated piece by piece as follows:
((8 * (y + z) ) + y) * x
((8 * 5) + y) * x
(40 + y) * x
42 * x
42
Operator Precedence- Evaluation Order

Order:
(1) [ ]  a[b]  a[1]
(2) = ( from the right)  b=0  return 0
 a[1] = 0
Basic Constructs

 They are taken from C-language


 Selection
if, if … else
switch (char/int exp)… case … default…
 Loops
for
do… while
while
Basic Logic Constructs
 They are the same with those in C-statements

An enhanced for loop

a 1 2 3 4 5

x 1
The String type

• A String represents a sequence of zero or


more Unicode characters.
• String name = "Steve";
• String s = “”;
• String s = null;
• String concatenation.
• String x = "foo“ + "bar“ + "!";
• Java is a case-sensitive language.
Type Conversions and Explicit Casting

* Widening Conversion: OK
• Narrowing conversion: Not
allowed. We must use
explicit casting.
• A boolean can not be
converted to any other
type.
• A non-boolean can be
converted to another non-
boolean type.

0000 0001

0000 0000

y n
Scope of a Variable

Scope of the
variable y

Scope of the
variable i
Input/Output Data (1)

 Class java.lang.System
 Class java.util.Scanner
Refer to Java documentation:
java.lang.String class,
- the format method,
- format string
for more details

n= sc.nextInt();
Input/Output Data (2)
PACKAG

import java.util.Scanner;
E

//Declaration of Scanner "variable"


Scanner scVar = new Scanner(System.in);

//Functionality provided
SYNTAX

scVar.nextInt();

scVar.nextDouble();

......
Input/Output Data (3)
import java.util.Scanner; // or import java.util.*;

public class TemperatureInteractive {

public static void main(String[] args) {

double fahrenheit, celsius;


Scanner sc = new Scanner(System.in);

System.out.print("Enter temperature in Fahrenheit: ");


fahrenheit = sc.nextDouble();

celsius = (5.0/9) * (fahrenheit – 32);


System.out.println("Celsius: " + celsius);
}
}

TemperatureInteractive.java

23
Input/Output Data (4)

 The statement
Scanner sc = new Scanner(System.in);
– Declares a variable “sc” of Scanner type
– The initialization “new Scanner(System.in)”
• Constructs a Scanner object
– We will discuss more about object later
• Attaches it to the standard input “System.in”
(which is the keyboard)
– This Scanner object sc will receive input from this source
• Scanner can attach to a variety of input sources;
this is just a typical usage

24
Input/Output Data (5)

 After proper initialization, a Scanner object


provides functionality to read value of
various types from the input source
 The statement
fahrenheit = sc.nextDouble();
– nextDouble() works like a function (called method
in Java) that returns a double value read interactively
– The Scanner object sc converts the input into the
appropriate data type and returns it
• in this case, user input from the keyboard is converted into a
double value 25
Input/Output Data (6)

 Typically, only one Scanner object is


needed, even if many input values are to
be read.
– The same Scanner object can be used to call
the relevant methods to read input values
 Note: In CodeCrunch, your program will
NOT work if you use more than one
Scanner object in your program.

[501043 Lecture 1: Intro to Java] 26


Input/Output Data (7)
 System.out is the predefined output device
– Refers to the monitor/screen of your computer

//Functionality provided
System.out.print( output_string );
SYNTAX

System.out.println( output_string );

System.out.printf( format_string, [items] );

Output:
System.out.print("ABC"); ABCDEF
System.out.println("DEF"); GHI
System.out.println("GHI"); Very C-like 3.142

System.out.printf("Very C-like %.3f\n", 3.14159);

27
Input/Output Data (8)
 Java introduces printf() in Java 1.5
– Very similar to the C version
 The format string contains normal characters and a number
of specifiers
– Specifier starts with a percent sign (%)
– Value of the appropriate type must be supplied for each specifier
 Common specifiers and modifiers:
%d for integer value
%f for double floating-point value %[-][W].[P]type

SYNTAX
%s for string
for boolean value
-: For left alignment
%b
W: For width
%c for character value
P: For precision

28
Elements of Java Style

• Proper Use of Indentation


• Statements within a block of code should be indented
relative to the starting/ending line of the enclosing
block.
• Use Comments Wisely
• Placement of Braces
• Opening brace at the end of the line of code that
starts a given block. Each closing brace goes on its
own line, aligned with the first character of the line
con.
• Descriptive Variable Names
Elements of Java Style
• Java Identifier Rule:
– May consist of letters (‘a’ – ‘z’, ‘A’ – ‘Z’), digit characters
(‘0’ – ‘9’), underscore (_) and dollar sign ($)
– Cannot begin with a digit character
– Class name: UpperCamelCase
• Eg: Math, HelloWorld, ConvexGeometricShape
– Variable name: LowerCamelCase
• Eg: countDays, innerDiameter, numOfCoins
– Constant: All uppercase with underscore
• Eg: PI, CONVERSION_RATE, CM_PER_INCH
Pass Arguments to the method main
Pass
Arguments to
the method
main
What Is a Package?
• A package is a namespace that organizes
a set of related classes and interfaces.
• The Java platform provides an enormous
class library (a set of packages) suitable
for use in your own applications called
API.
• For example, a String object contains state and
behavior for character strings.
User-Defined Package
• Add a Java
class

If package is used, it must be


the first line in Java code
User-Defined Package
Summary
• The core concepts behind object-oriented
programming: objects, interfaces, classes,
and inheritance.
• The traditional features of the language,
including variables, arrays, data types,
operators, and control flow.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy