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

Chpater 2 Basic in Java Programming

The document discusses the basic structure and components of a Java program, including that every Java program must contain a class with a main method, and covers Java programming concepts like variables, data types, operators, and how to compile and run a simple "Hello World" Java application. It provides an overview of key elements needed to understand the basics of writing Java code.

Uploaded by

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

Chpater 2 Basic in Java Programming

The document discusses the basic structure and components of a Java program, including that every Java program must contain a class with a main method, and covers Java programming concepts like variables, data types, operators, and how to compile and run a simple "Hello World" Java application. It provides an overview of key elements needed to understand the basics of writing Java code.

Uploaded by

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

Chapter two

Java Basics

1
Java program structure
• Java is a pure object oriented language,

• Everything is written within a class block.

[ 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 {

public static void main(String[] args)


{

System.out.println("Hello World!");

}
• Save this file as HelloWorld.java (watch capitalization)

3
• Java is about creating and using classes

• Classes, methods and related statements are enclosed


4
between { ... }
main - A Special Method
• The main method is where a Java program always starts when you run a
class file with the java command

• The main method has a strict signature which must be followed:

public static void main(String[] args)


{
. . .
}

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

• In this example args[0] will contain the String “Aman", and


the output of the program will be "Hi, Aman".
6
Compiling and Running
Your First Program
• Open the command prompt in Windows
• To run the program that you just wrote, type at the command
prompt:
cd c:\java
• Your command prompt should now look like this:
c:\java>
• To compile the program that you wrote, you need to run the
Java Development Tool Kit Compiler as follows:
At the command prompt type:
c:\java> javac HelloWorld.java
• You have now created your first compiled Java program named
HelloWorld.class
• To run your first program, type the following at the command
prompt:
c:\java>java HelloWorld
• Although the file name includes the .class extension , this part of the name must be7left
off when running the program with the Java interpreter.
• Class name must be the same as the file name where the
class lives. Eg. A class named MyFirstClass has to be in
the file called MyFirstClass.java.
• A program can contain one or more class definitions but
only one public class definition.
• The program can be created in any text editor.

• If a file contains multiple classes, the file name must be


the class name of the class that contains the main method

8
• Java program = Comments + Token(s) + white space

• Comments

– Java supports three types of comment delimiters

– The /* and */ - enclose text that is to be treated as a


comment by the compiler
– // - indicate that the rest of the line is to be treated as a
comment by the Java compiler
– the /** and */ - the text is also part of the automatic
class documentation that can be generated using
JavaDoc.
9
Tokens
• The smaller individual units inside a program that the compiler
recognizes when building up the program
•  Five types of Tokens in Java:

– Reserved keywords

– Identifiers

– Literals

– operators

– separators

10
Reserved keywords
• words with special meaning to the compiler

• The following keywords are reserved in the Java language. They


can never be used as identifiers:
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void violate while
• Some are not used but are reserved for further use. (Eg.: const,
11
goto)
Identifiers
• Programmer given names

• Identify classes, methods, variables, objects, packages.

• Identifier Rules:

– Must begin with

• Letters , Underscore characters ( _ ) or Any currency symbol

– Remaining characters
•   Letters

•   Digits

– As long as you like!! (until you are tired of typing)

– The first letter can not be a digit


12
– Java is case sensitive language
• Identifiers’ naming conventions

– Class names: starts with cap letter and should be inter-


cap e.g. StudentGrade
– Variable names: start with lower case and should be
inter-cap e.g. varTable
– Method names: start with lower case and should be
inter-cap e.g. calTotal
– Constants: often written in all capital and use
underscore if you are using more than one word.

13
Literals
• Explicit (constant) value that is used by a program

• Literals can be digits, letters or others that represent


constant value to be stored in variables
– Assigned to variables

– Used in expressions

– Passed to methods

• E.g.

– Pi = 3.14; // Assigned to variables


– C= a * 60; // Used in expressions
– Math.sqrt(9.0); // Passed to methods 14
Operator
• symbols that take one or more arguments
(operands) and operates on them to produce a
result
• 5 Operators
– Arithmetic operators

– Assignment operator

– Increment/Decrement operators

– Relational operators

– Logical operators 15
Arithmetic expressions and operators
• Common operators for numerical values

– Multiplication (*)

– Division (/)

– Addition (+)

– Subtraction (-)

– Modulus (%) the remainder of dividing op1 by op2

• A unary operator requires one operand.

• A binary operator requires two operands.

• A tertiary operator requires three operands .

16
Arithmetic Operator precedence
• Order of Operations (PEMDAS)

1. Parentheses

2. Exponents

3. Multiplication and Division from left to right

4. Addition and Subtraction from left to right

17
Assignment Operators
• Assigns the value of op2 to op1.

– op1 = op2;

• Short cut assignment operators

– E.g. op1 += op2 equivalent 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

|| op1 || op2 either op1 or op2 is 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)

• Java will evaluate these expressions from left to right


and so will evaluate
a before (b++ > 3)
x before y

• Java performs short-circuit evaluation:


it evaluates && and || expressions from left to right
and once it finds the result, it stops. 23
Short-Circuit Evaluations
(a && (b++ > 3))

What happens if a is false?


• Java will not evaluate the right-hand expression (b++ > 3) if the
left-hand operator a is false, since the result is already
determined in this case to be false. This means b will not be
incremented!

(x || y++)

What happens if x is true?


• Similarly, Java will not evaluate the right-hand operator y if the
left-hand operator x is true, since the result is already
determined in this case to be true. 24
Operator Precedence
• Arithmetic Operators
• Relational Operators
• Assignment Operators

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

– named memory location that can be assigned a value

– an item of data named by an identifier

– An object stores its state in 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

• Comment - describes its purpose, helps in understanding the program

– 27
• Best practice:

– Choose names that makes the purpose of the variable easy to


understand.
– Write a short comment for each variable unless the purpose is
obvious from its name.
• Declaring and initializing a variable:

– Assignment - placing a value in the memory location referred to


by the variable
– Initialization - the first assignment to a variable

28
• There are three kinds of variables in Java.

• 1. Instance variables: variables that hold data for an

instance of a class.

• 2. Class variables: variables that hold data that will be

shard among all instances of a class.

• 3. Local variables: variables that pertain only to a block of

code.

29
• Choosing variable names:

• Remember what Java accepts as valid names

– Names can contain letters and digits, but cannot start with a
digit.
– Underscore (_) is allowed, also as the first character of a name.

– Java distinguishes between upper and lower case letters in


names.
– Keywords like int cannot be used as variable names.

• Determine which of the following names are valid and follow


conventions.
– int teamId, Team_Leader, 24x7, bestGuess!, MAX_COUNT;
30
Data types
• Java has two basic data types

– Primitive types

– Reference types

31
Keyword Description
Size/Format
(integers)

byte Byte-length integer 8-bit two's complement

short Short integer 16-bit two's complement

int Integer 32-bit two's complement

long Long integer 64-bit two's complement

(real numbers)

float Single-precision floating point 32-bit IEEE 754

double Double-precision floating point 64-bit IEEE 754

(other types)

char A single character 16-bit Unicode character

boolean A boolean value (true or false) true or false 32


• Boolean type has a value true or false (there is no conversion b/n
Boolean and other types).
• All integers in Java are signed, Java doesn’t support unsigned
integers.
• Reference Type

– Arrays, classes, and interfaces are reference types

– The value of a reference type variable, in contrast to that of a


primitive type, is a reference to (an address of) the value or set of
values represented by the variable

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

all references null 34


Scope and Lifetime of variables
• scope is the region of a program within which the variable can be
referred to by its simple name
• scope also determines when the system creates and destroys
memory for the variable
– A block defines a scope. Each time you create a block of code,
you are creating a new, nested scope.
– Objects declared in the outer block will be visible to code within
the inner block down from the declaration. (The reverse is not
true)

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

• Expression is segments of code that perform computations and return


values .
• Expressions can contain: Example:

– a number literal, 3.14

– a variable, count

– a method call, Math.sin(90)

– an operator between two expressions (binary operator), phase +


Math.sin(90)

– an operator applied to one expression (unary operator), -discount

– expressions in parentheses. (3.14-amplitude)


38
Statements
• Roughly equivalent to sentences in natural languages

• Forms a complete unit of execution.

• terminating the expression with a semicolon (;)

• Three kinds of statements in java


– expression statements
– declaration statements
– control flow statements

• expression statements
– Null statements
– Assignment expressions
– Any use of ++ or –
– Method calls
– Object creation expressions 39
• Example

– aValue = 8933.234; //assignment statement


– aValue++; //increment statement
– System.out.println(aValue); //method call statement
– Integer integerObject = new Integer(4); //object creation

• A declaration statement declares a variable

– double aValue = 8933.234; // declaration statement


• A control flow statement regulates the order in which statements get
executed
– E.g - if, for
40
Conversion between primitive data types
• Evaluation of an arithmetic expression can results in implicit
conversion of values in the expression.
– Integer arithmetic yields results of type int unless at least on of the
operands is of type long.
– Floating-point arithmetic yields results of type double if one of the
operands is of type double.
• Conversion of a "narrower" data type to a "broader" data type is
(usually) done without loss of information, while conversion the other
way round may cause loss of information.
• The compiler will issue a error message if such a conversion is
illegal. 41
• Example
• int i = 10;
• double d = 3.14;
• d = i; // OK!
• i = d; // Not accepted without explicit conversion (cast)
• i = (int) d; // Accepted by the compiler
• Explicit type casting
– Syntax:
• (<dest-type>)<var_Idf or value>.
• Example:
– float f =3.5f; int x = (int)2.7;
– f = (float)2.9;
– float x=98;
– byte b=2;
– float y=x+b;
– b = (byte)y;
42
• Java Arrays
– Normally, an array is a collection of similar type of elements
which have a contiguous memory location.
• Java array is an object which contains elements of a similar
data type. Additionally, The elements of an array are stored in a
contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of
elements in a Java array.
• Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index and
so on.

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“

Syntax to Declare an Array in Java


dataType[] arr; (or)  
dataType []arr; (or)  
dataType arr[]; 

45
• Instantiation of an Array in Java
arrayRefVar=new datatype[size]; 

The two steps can be done together:


int numbers[ ]=new int[10];
or
int[ ] numbers=new int[10];

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 };

Automatic Initialization of Arrays:


If not programmer-initialized, array elements will be automatically
initialized as follows:
type default
initialization
integer 0
boolean false
char null
String null
object null
48
class Testarray1{  
public static void main(String args[]){  
int a[]={33,3,4,5};//
declaration, instantiation and initialization  
//printing array  
for(int i=0;i<a.length;i++)//
length is the property of array  
System.out.println(a[i]);  
}}

49
ArrayIndexOutOfBoundsException

•The Java Virtual Machine (JVM) throws an


ArrayIndexOutOfBoundsException if length of the
array in negative, equal to the array size or greater
than the array size while traversing the array.
Example:
public class TestArrayException{  
public static void main(String args[]){  
int arr[]={50,60,70,80};  
for(int i=0;i<=arr.length;i++){  
System.out.println(arr[i]);  
}  
}} 50
ArrayIndexOutOfBoundsExcepti
on
The Java Virtual Machine (JVM)
throws an
ArrayIndexOutOfBoundsException
if length of the array in negative,
equal to the array size or greater
than the array size while traversing
the array.

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

• Narrowing Casting (manually) - converting a larger type to a smaller


size type
double -> float -> long -> int -> char -> short -> byte

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:

double myDouble = 9.78; int myInt = (int)


myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9

56
Conversion using Methods

Method Description EXample


Integer.parseInt() Converts String to int – String str = "1050"; int
returs primitive int inum =
Integer.parseInt(str);
//return primitive
Long.parseLong() returns an Long object String longStr =
"1456755"; long ilong =
Long.parseLong(longStr);
//return primitive
System.out.println(ilong);
Long olong =
Long.valueOf(longStr);
//return object
System.out.println(olong);

57
Conversion using Methods

Method Description EXample


Integer.parseInt() Converts String to int – String str = "1050"; int
returs primitive int inum =
Integer.parseInt(str);
//return primitive
Integer.valueOf()  returns an Integer object String str = "1050"; int
inum =
Integer.parseInt(str);
//return primitive

Integer onum =
Integer.valueOf(str);
//return object
System.out.println(onum);

58
Conversion using Methods

Method Description EXample


Converts String to int – String str = "1050"; int
returs primitive int inum =
Integer.parseInt(str);
//return primitive
Integer.valueOf()  returns an Integer object String str = "1050"; int
inum =
Integer.parseInt(str);
//return primitive

Integer onum =
Integer.valueOf(str);
//return object
System.out.println(onum);

59
Conversion using Methods

Method Description EXample


Float.parseFloat() method.
 Float.valueOf()

Double.parseDouble() ,

 Double.valueOf()

60

You might also like