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

Session02-Learning The Java Language

This document discusses key concepts in the Java language covered in Session 02, including variables and naming conventions, primitive data types, arrays, strings, expressions, and operators. The session objectives are to learn Java language basics like variables, data types, literals, arrays, importing, classes, argument passing, garbage collection, control flow statements, and loop statements. It provides examples and explanations of these fundamental Java concepts.

Uploaded by

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

Session02-Learning The Java Language

This document discusses key concepts in the Java language covered in Session 02, including variables and naming conventions, primitive data types, arrays, strings, expressions, and operators. The session objectives are to learn Java language basics like variables, data types, literals, arrays, importing, classes, argument passing, garbage collection, control flow statements, and loop statements. It provides examples and explanations of these fundamental Java concepts.

Uploaded by

tuan nguyen anh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Session 02

Learning the Java Language

(http://docs.oracle.com/javase/tutorial/java/index.html)

Session 02 - Learning the Java


Language 
Objectives
• Java Language Basics.
 Variables and Naming
 Operators
 Primitive Data Types
 Literals
 Arrays
 Importing
 Class Fundamentals
 Argument Passing: By Reference or by Value
 Garbage Collection
 Control flow statements
 Loop Statements

Session 02 - Learning the Java


Language 
Java variable
• A Java variable is a piece of memory that can contain a data
value. A variable thus has a data type.
• Syntax
• DataType nameVariable ;
• Datatype has Primary DataType and Reference DataType

Session 02 - Learning the Java


Language 
Java variable
• Variable naming conventions
• A particular name deemed valid by the Java compiler.
• Must start with either an alphabetic character, an
underscore, or a dollar sign, and may contain any of these
characters plus numeric digits.
• No other characters are allowed in variable names.
• Begin with lower letter, for example
• int numOfStudent;
• Does a particular valid name adhere to the naming
convention that has been adopted by the OOP community
across all languages?

Session 02 - Learning the Java


Language 
Scope of a Variable
• executing. Once the method finishes
execution, these variables are destroyed. 
• Local variables 
• A local variable is the one that is declared
within a method or a constructor (not in
the header). The scope and lifetime are
limited to the method itself. One
important distinction between these three
types of variables is that access specifiers
• Global variables  can be applied to instance variables only
• Defined within a class itself and not in and not to argument or local variables. 
any method or constructor of the class.
• The lifetime of these variables is the
same as the lifetime of the object to
which it belongs.
• Argument variables 
• Defined in the header of constructor or a
method. The scope of these variables is
the method or constructor in which they
are defined. The lifetime is limited to02the
Session - Learning the Java
time for which the method keeps Language 
Primary DataType vs Reference DataType
• Datatype has:
Primary DataType
Reference DataType(Array, Class, String)

String s = “Hello World“;

Reference DataType
Primary DataType
Session 02 - Learning the Java
Language 
Primitive Data Types
• A primitive is a simple non-object data type that
represents a single value. Java’s primitive data types
are:
– boolean
– char
– byte
– short
– int
– long
– float
– double

Session 02 - Java Fundamentals


Primitive Data Types Example
import java.util.Scanner; System.out.println("Fullname:
public class Nhap { "+fullname);
public static void main(String[] args) { System.out.println("Name: "+name);
Scanner k = new Scanner(System.in); System.out.println("Age: "+age);
System.out.print("Enter fullname:"); System.out.println("Salary: "+salary);
String fullname = k.nextLine(); if (gender)
System.out.println("Gender: Male");
System.out.print("Enter name:"); else
String name = k.next(); System.out.println("Gender: Female");
String familyStatus = "";
System.out.print("Enter age:"); switch (status){
int age = k.nextInt(); case 's':
familyStatus = "Single";
System.out.print("Enter salary:"); break;
double salary = k.nextDouble(); case 'm':
familyStatus = "Married";
System.out.print("Enter gender:"); break;
boolean gender = k.nextBoolean(); //...
}
System.out.print("Enter family status System.out.println("Family Status:
(single s, married m...):"); "+familyStatus);
char status = k.next().charAt(0); }
}
Session 02 - Java Fundamentals
Reference DataType: Arrays
• 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.

Session 02 - Java Fundamentals


Reference DataType: Arrays
• Declaring a Variable to Refer to an Array
int[] anArray;
float anArrayOfFloats[];
• Creating, Initializing, and Accessing an Array
anArray = new int[10];
• Copying Arrays
• Use arraycopy method from System class.

Session 02 - Java Fundamentals


Array Example: Copy, Sort
Reference DataType: String
• 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.

Session 02 - Java Fundamentals


Java Expressions
• Java is an expression-oriented language. A simple expression
in Java is either:
• A number literal: 7, 8.5
• A boolean literal: false, true
• A char literal enclosed in single quotes: 'A', '3', '\t', '\n'
• A String literal enclosed in double quotes: "Java"
• The name of any declared constant: final int max = 100;
• The name of any properly declared variables: int x;
• Expressions consist of variables, literals, constant,
operators and method calls that evaluates to a single
value: i++
x+2
Session 02 - Java Fundamentals
Java Operators
 Arithmetic Operator: +, -, *, /, %
for all floating-point and integer numbers (including char),  the operator result is a
floating point or integer number.
Ex: 14 % 4 14/4.0
14/4 14.0/4
14.0/4.0
 Increment ++op/op++, Decrement Operator: --op/op--
Increment and decrement operators can be placed before (prefix) or after (postfix) the
variable they apply to.
++/--op: the operator is applied before the rest of the expression is evaluated
op++/--: the operator is applied after the expression is evaluated.
for integer numbers: increment/ decrement vsalue of variable by 1
for character: get the next or previous Unicode character

Ex: int x = 4, y; //x=4,y Ex: char s = 'a';


y = x++; //x=5, y =4 s++; //s=‘b’
y = ++x; //x=6, y =6 System.out.println(s); //in b
x++; //x=7 System.out.println(s+1); //in 99
System.out.println(--x); //x=6,in 6 s = (char) (s+1); //s=‘c’
Java Operators
 Comparison (relational) Operator
== equal to != not equal to
> greater than < less than
<= less than or equal to >= greater than or equal to
The operator result is a boolean.
Ex: 155 > 2.5 'B' < 'A'
 Logical Operator
is applied for boolean operands and the operator result is a boolean.
&&, & and ||, | or
! not ^ xor
op1 && op2 the result is true if both operands are true
op1 || op2 the result is false if both operands are false
op1 ^ op2 the result is true if the operands are different
!op if op = false then !op will return true and otherwise
Java Operators

Ex: 100 > 55 && 'B' < 'A'


mark >= 5 && mark < 7
c == 'y' || c == ‘Y'
Ex: int x=2, y=2;
x > 3 && x < ++y

The & operator always evaluates both expressions. The && operator


evaluates the second expression only if the first expression is true.

The | operator always evaluates both expressions. The || operator


evaluates the second expression only if the first expression is false.
Java Operators

 Assignment Operator
assigns the expression value on its right to the variable on its left.
Variable = Expression;
Ex : x = 10;
x = y = z = 0;

 Shorthand Assignment Operator


+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>= 
Ex: int a = 2;
a += 4; // a = a + 4;
Ex: char s ='A';
System.out.println(s+=4); //E
Casting
System.out.println(s+1); //70
rule Operand
s = (char) (s+1); promotion rule
System.out.println(s); //F
Java Operators
 Conditional operator ?:
is shorthand for if-then-else statement.
BooleanExpression ? Expression1 : Expression2
If the expression is true, the operator returns expression1, otherwise returns
expression2.
Ex: int x, a = 2, b = 5;
x = a > b ? a : b;
System.out.println(x);
System.out.println(a>b ? "a is greater than b" : "b is greater than a");
 Concatenation operator +
produces a new string by appending the second operand onto the end of the first
operand. It can concat not only string but primitive values also.
Ex: System.out.println("2 + 2 = "+2+2);
String s=50+30+" = "+40+40; 
Java Operators
 Bitwise and Bit shift operations on integral types.
Operator Description Usage
& bitwise AND op1 & op2
| bitwise OR op1 | op2
^ bitwise XOR op1 ^ op2
 bitwise NOT ~ op
<<  shift left n bit op << n
>>  shift right n bit op >> n
shift right n bit and fill 0 on the left side op >>> n
>>> 
Ex:
//000000102&000000112=000000102=2 //5>>2=5/22=1 000001012>>2=000000012
System.out.println(2 & 3); System.out.println(Integer.toBinaryString(5));
//000000102|000000112=000000112=3 System.out.println(Integer.toBinaryString(5>>2));
System.out.println(2 | 3); //-4>>1=-4/21=-2 111111002>>1=111111102
//000000102^000000112=000000012=1 System.out.println(Integer.toBinaryString(-4));
System.out.println(2 ^ 3); System.out.println(Integer.toBinaryString(-4>>1));
//~000000102=111111012 //4<<2=4*22=16 000001002<<2=000100002
System.out.println(~2); System.out.println(Integer.toBinaryString(4));
System.out.println(Integer.toBinaryString(4<<2));
Session 02 - Java Fundamentals
Precedence and associativity of operators
Operators in descending order of precedence
Level Operator Description Associativity
[] access array element
15 . access object member left to right
() parentheses
++ unary increment
-- unary decrement
+op unary plus
14 right to left
-op unary minus
! unary logical NOT
~ unary bitwise NOT
(type)op cast
13 right to left
new object creation
12 */% multiplicative left to right
+- additive
11 left to right
+ string concatenation
<< >>
10 shift left to right
>>>

Session 02 - Learning the Java Language 


Precedence and associativity of operators
Level Operator Description Associativity
< <=
9 > >= relational not associative
instanceof
==
8 equality left to right
!=
7 & bitwise AND left to right
6 ^ bitwise XOR left to right
5 | bitwise OR left to right
4 && logical AND left to right
3 || logical OR left to right
2 ?: ternary right to left
 =   +=   -=
*=   /=   %=
1 assignment right to left
&=   ^=   |=
<<=  >>= >>>=

Session 02 - Learning the Java Language 


Evaluating Expressions and Operator
Precedence
• The compiler evaluates following 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

Session 02 - Java Fundamentals


Type Conversions and Explicit Casting
• Automatic type conversion:
• int x;
• double y;
• y = 2.7;
• x = y; //also known as a narrowing conversion
• Explicit cast
• x = (type) expression;
• int x = (int)2.7;

Session 02 - Java Fundamentals


Statements
Statements can be simple statements, compound statements/ blocks, or
control structures
 Simple statements: is the most basic element in a Java program,
expressing an individual operation, must be terminated by a semi-colon (;)
 Declarations: int i = 1;
 Assignment operator: i = 7; i += 2;
 Increment, Decrement Operator: i++;
 Method call: System.out.println("Java programming");
 Compound statements/ Blocks: is a group of statements that is treated by
the compiler as if it were a single statement. Blocks begin with a { symbol,
end with a } symbol.
 Control Structures: Control the order of execution of statements
 Unconditional branching statements: break, continue, return.
 Conditional branching statements: if, switch
 Looping structure: for, while, do … while

Session 02 - Learning the Java


Language 
The if and if-else Statements
• Principal forms:

• Condition of an if statement
must be a Boolean expression
• Evaluates to true or
false

Session 02 - Java Fundamentals


Multiple Alternative if Statements

Session 02 - Java Fundamentals


Quadratic
import java.util.Scanner; double delta=b*b-4*a*c;
class Quadratic { if (delta<0)
public static void main(String[] args) { s="no root";
Scanner kbd = new Scanner(System.in); else if (delta==0)
System.out.print("Enter coefficient a:"); s="double root "+ -b/(2*a);
double a = kbd.nextDouble(); else
System.out.print("Enter coefficient b:"); s= "two roots x1= "+
double b= kbd.nextDouble(); (-b+Math.sqrt(delta))/(2*a)+
System.out.print("Enter coefficient c:"); " and x2= " +
double c=kbd.nextDouble(); if (-b-Math.sqrt(delta))/(2*a);
(a==0) }
if (b==0) System.out.println("Quadratic: "+s);
if (c==0) s="countless root"; }
else s="no root"; }
else s="one root "+ -c/b;
else { Session 02 - Learning the Java
Language 
The Switch Statement
• The switch statement provides
switch ( expression ){
another way to decide which
case value1 :
statement to execute next
statement-list1
• The switch statement break;
evaluates an expression, then case value2 :
attempts to match the result statement-list2
to one of several possible break;
cases case value3 :
statement-list3
• The match must be an exact break;
match. default:
statement-listn;
}

Session 02 - Learning the Java


Language 
Switch Statement
• The switch-expression must yield a value of char, byte, short, or int, String
type and must always be enclosed in parentheses.
• The value1, ..., and valueN must have the same data type as the value of
the switch-expression.
• The resulting statements in the case statement are executed when the
value in the case statement matches the value of the switch-expression.
(The case statements are executed in sequential order.)
• The keyword break is optional, but it should be used at the end of each case
in order to terminate the remainder of the switch statement. If the break
statement is not present, the next case statement will be executed.
Session 02 - Learning the Java
Language 
Switch statements Example

Session 02 - Java Fundamentals


break Statement
break statement: terminate immediately a loop or switch statement.

Session 02 - Learning the Java


Language 
The while Statement
• Provides a looping mechanism
– Executes statements repeatedly for as long as some condition
remains true
– If the condition of a while loop is false initially, the
statement is never executed
– Therefore, the body of a while loop will execute zero or
more times

Session 02 - Learning the Java


Language 
The while Statement Example

Session 02 - Learning the Java


Language 
The do-while Statement
• Also called a do-while loop
• Similar to a while statement,
except that the loop body is Statement(s)

executed at least once


• Syntax
true
do Continue
condition?
{
Statements; false

} while (condition); Next


• Don’t forget the semicolon! Statement

Session 02 - Learning the Java


Language 
The do-while Statement Example

Session 02 - Learning the Java


Language 
The for statement
• Combines counter initialization, condition test, and update
into a single expression
• Easy to create count-controlled loops

Session 02 - Learning the Java


Language 
The for walkthrough

Session 02 - Learning the Java


Language 
The for statement Example

Session 02 - Learning the Java


Language 
Nested for loops
• Nested loop: A loop placed inside another loop.
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
System.out.println(); // to end the line
}

• Output:
**********
**********
**********
**********
**********

• The outer loop repeats 5 times; the inner one 10 times.

Session 02 - Learning the Java


Language 
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++)
System.out.print("*");
System.out.println();
}

• Output:
*
**
***
****
*****

Session 02 - Learning the Java


Language 
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++)
System.out.print(i);
System.out.println();
}

• Output:
1
22
333
4444
55555

Session 02 - Learning the Java


Language 
The for each loop
• Java has a powerful looping construct that allows you to loop through
each element in an array (or any other collection of elements) without
having to fuss with index values.
• Syntax:
for (DataType variableName : Collection)
• The for loop sets the given variable to each element of the collection and
then executes the statement (which, of course, may be a block). The
collection expression must be an array or an object of a class that
implements the Iterable interface, such as ArrayList.

int sumOfLengths(String[] studentName) {


int totalLength = 0;
for (String name: studentName)
totalLength += name.length();
return totalLength;
}
Session 02 - Learning the Java
Language 
Printing to the Screen
• To print text messages to the screen:
– System.out.println(expression to be printed);
– Example:
• System.out.println("Hi!");
• System.out.println(x + y);
• System.out.println("The sum of x plus y is: " + x + y);
• System.out.println("Here's an example of how " +
"to break up a long print statement " + "with
plus signs.");

Session 02 - Learning the Java


Language 
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

Session 02 - Learning the Java


Language 
Summary
• The traditional features of the language, including variables,
arrays, data types, operators, and control flow.

Session 02 - Learning the Java


Language 

You might also like