Chpater 2 Basic in Java Programming
Chpater 2 Basic in Java Programming
Java Basics
1
Java program structure
• Java is a pure object oriented language,
[ Documentation]
[package statement]
[import statement(s)]
[interface statement]
[class definition]
main method class definition
2
Your First Java Program
• // your first java application
import java.lang;
class HelloWorld {
System.out.println("Hello World!");
}
• Save this file as HelloWorld.java (watch capitalization)
3
• Java is about creating and using classes
5
main cont …
class SayHi {
public static void main(String[] args) {
System.out.println("Hi, " + args[0]);
}
}
• When java Program arg1 arg2 … argN is typed on the
command line, anything after the name of the class file is
automatically entered into the args array:
java SayHi Aman
8
• Java program = Comments + Token(s) + white space
• Comments
– Reserved keywords
– Identifiers
– Literals
– operators
– separators
10
Reserved keywords
• words with special meaning to the compiler
• Identifier Rules:
– Remaining characters
• Letters
• Digits
13
Literals
• Explicit (constant) value that is used by a program
– Used in expressions
– Passed to methods
• E.g.
– Assignment operator
– Increment/Decrement operators
– Relational operators
– Logical operators 15
Arithmetic expressions and operators
• Common operators for numerical values
– Multiplication (*)
– Division (/)
– Addition (+)
– Subtraction (-)
16
Arithmetic Operator precedence
• Order of Operations (PEMDAS)
1. Parentheses
2. Exponents
17
Assignment Operators
• Assigns the value of op2 to op1.
– op1 = op2;
18
Increment/Decrement operators
• op++
– Increments op by 1;
– evaluates to the value of op before it was incremented
• ++op
– Increments op by 1;
– evaluates to the value of op after it was incremented
• op--
– Decrements op by 1;
– evaluates to the value of op before it was decremented
• --op
– Decrements op by 1;
– evaluates to the value of op after it was decremented
19
Relational Operators
• Refers to the relationship that values can have with each other
• Evaluates to true or false
• All relational operators are binary.
• E.g. int i = 1999;
boolean isEven = (i%2 == 0); // false
float numHours = 56.5;
boolean overtime = numHours > 37.5; // true
20
Logical Operators
• Refers to the way in which true and false values can be
connected together
Operator Use Returns true if
&& op1 && op2 op1 and op2 are both true, conditionally evaluates op2
! ! op op is false
& op1 & op2 op1 and op2 are both true, always evaluates op1 and op2
| op1 | op2 either op1 or op2 is true, always evaluates op1 and op2
^ op1 ^ op2 if op1 and op2 are different--that is if one or the other of the operands is true but not both
21
• Precedence rules:
1. Negation
2. Conditional And
3. Conditional Or
• The binary operators Conditional Or (||) and And (&&) associate
from left to right.
• The unary operator Negation (!) associate from right to left.
22
Using && and ||
• Examples:
(a && (b++ > 3))
(x || y)
(x || y++)
25
Separators
• Indicate where groups of codes are divided and arranged
Name Symbol
Parenthesis ()
braces {}
brackets []
semicolon ;
comma , ,
.
period
26
Variables and Data Types
• Variables
– Declaring a variable:
• Variable name - unique name of the memory location
• Data type (or type) - defines what kind of values the variable can hold
– 27
• Best practice:
28
• There are three kinds of variables in Java.
instance of a class.
code.
29
• Choosing variable names:
– Names can contain letters and digits, but cannot start with a
digit.
– Underscore (_) is allowed, also as the first character of a name.
– Primitive types
– Reference types
31
Keyword Description
Size/Format
(integers)
(real numbers)
(other types)
33
Default values
• We can not use variables with out initializing them in Java.
Default
Primitive
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char null
boolean false
35
– Variables are created when their scope is entered, and
destroyed when their scope is left. This means that a
variable will not hold its value once it has gone out of
scope.
– Variable declared within a block will lose its value
when the block is left. Thus, the lifetime of a variable is
confined to its scope.
– You can’t declare a variable in an inner block to have
the same name as the one up in an outer block. But it
is possible to declare a variable down outside the inner
block using the same name.
36
Blocks
• a group of zero or more statements between balanced braces
• E.g
if (Character.isUpperCase(aChar))
{
System.out.println("The character " + aChar + " is
upper case.");
}
else
{
System.out.println("The character " + aChar + " is
lower case.");
37
}
Expression
• Combine literals, variables, and operators to form expressions
– a variable, count
• expression statements
– Null statements
– Assignment expressions
– Any use of ++ or –
– Method calls
– Object creation expressions 39
• Example
43
• We can store primitive values or objects in an
array in Java.
• we can also create single dimentional or
multidimentional arrays in Java.
• Disadvantages
• Size Limit: We can store only the fixed size of
elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework
is used in Java which grows automatically.
44
• Obtaining a Java array is a two step process:
1. Declare a variable that can reference an array
object
2. Create the array object by using operator "new“
45
• Instantiation of an Array in Java
arrayRefVar=new datatype[size];
46
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
47
Declaration, Instantiation and Initialization of Java
Array
int[] nums={ 30,50,-23,16 };
49
ArrayIndexOutOfBoundsException
51
• Multidimensional Array in Java
• In such case, data is stored in row and column based
index (also known as matrix form).
• Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
52
• Example to instantiate Multidimensional Array
in Java
• int[][] arr=new int[3][3];//3 row and 3 column
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
53
• Java Type Casting
• Type casting is when you assign a value of one primitive data type to
another type.
• In Java, there are two types of casting:
• Widening Casting (automatically) - converting a smaller type to a
larger type size
byte -> short -> char -> int -> long -> float -> double
54
• Widening or Implicit Casting
– Widening casting is done automatically when
passing a smaller size type to a larger size type:
Example:
int myInt = 9; double myDouble = myInt; //
Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
55
• Narrowing or Explicit Casting
– Narrowing casting must be done manually by
placing the type in parentheses in front of the
value:
56
Conversion using Methods
57
Conversion using Methods
Integer onum =
Integer.valueOf(str);
//return object
System.out.println(onum);
58
Conversion using Methods
Integer onum =
Integer.valueOf(str);
//return object
System.out.println(onum);
59
Conversion using Methods
Double.parseDouble() ,
Double.valueOf()
60