• No results found

Type And Variables, Java Operators,

N/A
N/A
Protected

Academic year: 2022

Share "Type And Variables, Java Operators,"

Copied!
67
0
0

Loading.... (view fulltext now)

Full text

(1)

Java Language Basics:

Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Expressions, Statements and Arrays.

(2)

Introduction to Java Technology

Java technology is:

 A programming language

 A development environment

 An application environment

 A deployment environment

 It is similar in syntax to C++.

It is used for developing both applets and

applications

(3)

Primary Goals of the Java Technology

 Provides an easy-to-use language by:

◦ Avoiding many pitfalls of other languages

◦ Being object-oriented

◦ Enabling users to create streamlined and clear code

 Provides an interpreted environment for:

◦ Improved speed of development

◦ Code portability

(4)

Primary Goals of the Java Technology

 Loads classes dynamically; that is, at the time they are actually needed

 Supports changing programs dynamically during runtime by loading classes from disparate sources

 Furnishes better security

(5)

Primary Goals of the Java Technology

 The following features fulfill these goals:

◦ The Java Virtual Machine

◦ Garbage collection

◦ The Java Runtime Environment (JRE)

(6)

Feature of Java

Simple

Object-Oriented

Platform independent

Secured

Robust

Architecture neutral

Portable

Dynamic

Interpreted

High Performance

Multithreaded

Distributed

(7)

The Java Virtual Machine

 Provides hardware platform specifications

 Reads compiled byte codes that are platform-independent

 Is implemented in a Java technology

development tool or a Web browser

(8)

Garbage collection

 Allocated memory that is no longer needed should be deallocated.

 In other languages, deallocation is the programmer’s responsibility.

 The Java programming language provides a system-level thread to track memory

allocation.

(9)

Garbage collection

 Garbage collection has the following characteristics:

◦ Checks for and frees memory no longer needed Is done automatically

◦ Can vary dramatically across JVM

implementations

(10)

The Java Runtime Environment

The Java application environment performs as

follows:

(11)

JVM™ Tasks

 The JVM performs three main tasks:

 Loads code

 Verifies code

 Executes code

(12)

The Class Loader

 Loads all classes necessary for the execution of a program

 Maintains classes of the local file system

in separate namespaces

(13)

The Bytecode Verifier

 Ensures that:

◦ The code adheres to the JVM specification.

◦ The code does not violate system integrity.

◦ The code causes no operand stack overflows.

◦ The parameter types for all operational code are correct.

◦ No illegal data conversions (the conversion of

integers to pointers) have occurred.

(14)

Primitive Data Type

 They are in-built part of the language.

 These data type have the same size and

characteristics no matter what operating

system and platform you are on.

(15)

Primitive Data Types

 Primitive Data Types

◦ Logical – boolean

◦ Textual – char

◦ Integral – byte, short, int, and long

◦ Floating – double and float

(16)

Logical

 The boolean primitive has the following characteristics:

The boolean data type has two literals, true and false.

 For example, the statement:

◦ boolean truth = true;

 declares the variable truth as boolean type

and assigns it a value of true.

(17)

Textual – char

The textual char primitive has the following characteristics:

Represents a 16-bit Unicode character

Must have its literal enclosed in single quotes (’ ’)

Uses the following notations:

◦ 'a' The letter a

◦ '\t' The tab character

◦ '\u????' A specific Unicode character, ????, is replaced with exactly four hexadecimal digits .

For example, ’\u03A6’ is the Greek letter phi [Φ].

(18)

Textual - String

 The textual String type has the following characteristics:

 Is not a primitive data type; it is a class

 Has its literal enclosed in double quotes ("

")

◦ "The quick brown fox jumps over the lazy dog."

 Can be used as follows:

 String greeting = "Good Morning !! \n";

 String errorMessage = "Record Not Found

!";

(19)

Integral – byte, short, int, and long

 The integral primitives have the following characteristics:

◦ Integral primates use three forms: Decimal, octal, or hexadecimal

2 : in Decimal

02: in Octal

0XB: in Hexadecimal

◦ Literals have a default type of int.

◦ Literals with the suffix L or l are of type long.

(20)

Integral:

 Byte: 8 bits

 Short: 16 bits

 int: 32 bits

 long: 64 bits

(21)

Floating – double and float

The floating point primitives have the following characteristics:

Floating-point literal includes either a decimal point or one of the following:

E or e (add exponential value)

F or f (float)

D or d (double)

◦ 3.14: A simple floating-point value (a double)

◦ 6.02E23: A large floating-point value

◦ 2.718F: A simple float size value

(22)

Floating – double and float

 Literals have a default type of double.

 Floating-point data types have the following sizes:

Float Length Name or Type

◦ 32 bits: float

◦ 64 bits: double

(23)

Java Reference Types

 In Java technology, beyond primitive types all others are reference types.

A reference variable contains a handle to

an object.

(24)

Class Type

 In addtion to the 8 basic data types, a variable can have a class as its type,

◦ String myName=“abhilasha”;

◦ Color Hair;

(25)

Identifiers

Identifiers have the following characteristics:

Are names given to a variable, class, or method

Can start with a Unicode letter, underscore (_), or dollar sign ($)

Are case-sensitive and have no maximum length

Examples:

◦ identifier

◦ userName

◦ user_name

◦ _sys_var1

◦ $change

(26)

Variable

 A variable is a place where information

can be stored while a program is running.

The value can be changed at any point in the program.

 There are three types of variables in Java

◦ Instance Variable

◦ Class Variable

◦ Local Variable

(27)

Variable

 Instance variable: These are used to define an object’s attribute.

 Class Variable: These are used to define the property of class

 Local Variables: these are used inside

method definition or even smaller blocks

of statements with in a method.

(28)

Global Variable

 Unlike other programming languages Java

doesn’t support global variable, a variable

can be used in all parts of progarm.

(29)

Comments

The three permissible styles of comment in a Java technology

program are:

First Type:

◦ // comment on one line

Second Type:

◦ /* comment on one

◦ * or more lines

◦ */

Third Type:

◦ /** documentation comment

◦ * can also span one or more lines

◦ */

(30)

Operators

 These are special symbols used for

mathematical functions, some types of assignment statements, and logical

comparisons.

(31)

Arithmetic

 Addition: +

 Subtraction: -

 Multiplication: *

 Division: /

 Modulus: %

(32)

Assignment

 +=

 -=

 *=

 /=

 =

(33)

Incrementing and Decrementing

 These are called prefix operators if listed before a variable name, and postfix

operators if listed after a name.

(34)

Comparison Operators

 Equal: ==

 Not Equal: !=

 Less than: <

 Greater than: >

 Less than or equal to: <=

 Greater than or equal to: >=

(35)

Logical Operators

 and: &&

 or: ||

(36)

Expressions

 Expressions perform operations on data and move data around. Some expressions will be evaluated for their results, some

for their side effects, some for both.

 An expression can have three kinds of result:

◦ a value, such as the result of: (4 * i)

◦ a variable, such as the result of: i = 4

◦ nothing (in the case of an invocation of a

method declared as void)

(37)

Expressions

 An expression that results in a variable is called an lvalue in C++ and many other languages.

 A variable expression in Java is the same thing, the Java Language Specification just uses the name variable instead of lvalue.

Such an expression can be used on the left hand side of an assignment operator.

Side effects come about when an expression includes an assignment, increment,

decrement, or method invocation.

(38)

Statements

 A Java method body is a series of zero or more statements.

 In the Java programming language,

statements are the fundamental unit of execution.

 All statements except blocks are

terminated by a semicolon.

(39)

Statements

 Statements are executed for their effects;

they do not have values.

 There are many different kinds of statements in Java:

◦ local variable declaration statements

◦ the if and if-else statements

◦ the while statement

◦ the do-while statement

◦ the for statement

◦ the switch statement

◦ the break statement

◦ the continue statement

(40)

Variable declaration Statement

 int i;

 String A=“BCA 6 SEM”;

 double d=3.0;

 boolean b=“true”;

(41)

Simple if, else Statements

The if statement syntax:

if ( <boolean_expression> )

<statement_or_block>

Example:

if ( x < 10 )

System.out.println(“x less than 10?");

or (recommended):

if ( x < 10 ) {

System.out.println(“x less than 10?");

}

(42)

Complex if, else Statements

The if-else statement syntax:

if ( <boolean_expression> )

<statement_or_block>

else

<statement_or_block>

Example:

if ( x < 10 ) {

System.out.println("Are you finished yet?");

} else {

System.out.println("Keep working...");

}

(43)

Complex if, else Statements

The if-else-if statement syntax:

if ( <boolean_expression> )

<statement_or_block>

else if ( <boolean_expression> )

<statement_or_block>

Example:

int count = getCount(); // a method defined in the class

if (count < 0) {

System.out.println("Error: count value is negative.");

} else if (count > getMaxCount()) {

System.out.println("Error: count value is too big.");

} else {

System.out.println("There will be " + count +

" people for lunch today.");

}

(44)

Switch Statements

The switch statement syntax:

switch ( <expression> ) {

case <constant1>:

<statement_or_block>*

[break;]

case <constant2>:

<statement_or_block>*

[break;]

default:

<statement_or_block>*

[break;]

}

(45)

Looping Statements

The for loop:

for (<init_expr>;<test_expr>;

<alter_expr> )

<statement_or_block>

Example:

for ( int i = 0; i < 10; i++ )

System.out.println(i + " squared is " + (i*i));

or (recommended):

for ( int i = 0; i < 10; i++ ) {

System.out.println(i + " squared is " + (i*i));

}

(46)

Looping Statements

 The while loop:

while ( <test_expr> )

<statement_or_block>

 Example:

 int i = 0;

 while ( i < 10 ) {

 System.out.println(i + " squared is " + (i*i));

 i++;

 }

(47)

Looping Statements

The do/while loop:

do

<statement_or_block>

while ( <test_expr> );

Example:

int i = 0;

do {

System.out.println(i + " squared is " + (i*i));

i++;

} while ( i < 10 );

(48)

Special Loop Flow Control

The break [<label>]; command

• The continue [<label>]; command

(49)

Special Loop Flow Control

break quits the loop without executing the rest of the statements in the loop.

continue stops the execution of the

current iteration and goes back to the

beginning of the loop to begin the next

iteration.

(50)

The break Statement

do {

statement;

if ( condition ) {

break;

}

statement;

} while ( test_expr );

(51)

Example

(52)

Output

(53)

Example

(54)

Output

(55)

Continue

do {

statement;

if ( condition ) { continue;

}

statement;

} while ( test_expr );

(56)

Example

(57)

Output

(58)

Array

 Arrays are used typically to group objects of the same type.

 Arrays enable you to refer to the group of objects by a common name.

 The declaration of an array creates a

reference that you can use to refer to an array.

 The actual memory used by the array elements is allocated dynamically either by a new statement or by an array

initializer.

(59)

Declare Array

 Declare arrays of primitive or reference types:

◦ char s[];

◦ Point p[];

◦ char[] s;

◦ Point[] p;

(60)

Initializing Array

Use the new keyword to create an array object.

For example, a primitive (char) array:

public char[] createArray()

{

char[] p;

char s[]=new char[26];

p = new char[26];

for ( int i=0; i<26; i++ )

{

s[i] =i;

}

return s;

}

(61)

Examples:

 String

names={“name1”,”name2”,”name3”};

 This code is equivalent to:

◦ names=new String[3];

◦ names[0]=“name1”;

◦ names[1]=“name2”;

◦ names[2]=“name3”;

(62)

Multidimensional Array

 Java language does not provide

multidimensional array in the same way that other language do.

 In this you can create arrays of arrays.

 Example:

 int[][] twoDim = new int[4][];

 twoDim[0] = new int[5];

 twoDim[1] = new int[50];

 int[][] twoDim = new int[][4]; //illegal

(63)

Multidimensional Array

 The object that is created by the first call to new is an array that contains four

elements.

 Each element is a null reference to an

element of type array of int and you must

initialize each element separately so that

each element points to its array.

(64)

Multidimensional Array

 Because of this separation, you can create non-rectangular arrays of arrays. Example:

 twoDim[0] = new int[2];

 twoDim[1] = new int[4];

 twoDim[2] = new int[6];

 twoDim[3] = new int[8];

 • Array of four arrays of five integers each:

 int[][] twoDim = new int[4][5];

(65)

Array bound

 All array subscripts begin at 0:

 public void printElements(int[] list) {

for (int i = 0; i < list.length; i++) { System.out.println(list[i]);

}

}

(66)

Using the Enhanced for Loop

Java 2 Platform, Standard Edition (J2SE) version 5.0

introduced an enhanced for loop for iterating over arrays:

public void printElements(int[] list) {

for ( int element : list ) {

System.out.println(element);

}

}

The for loop can be read as for each element in

list do.

(67)

Array Resizing

 You cannot resize an array.

 You can use the same reference variable to refer to an entirely new array, such as:

 int[] myArray = new int[6];

 myArray = new int[10];

References

Related documents

The VX Cycle offers a broad range of scales for the cost-effective production of LNG/CCNG, and the Cycle can be integrated with existing CNG stations, pipeline compressor stations

The Java Runtime Environment (JRE), which includes the Java Plug-in software and the Java Virtual Machine components needed to run Java Technology based applets in a web browser..

Android runtime consists of Dalvik virtual machine and core java libraries. Dalvik virtual machine is a type of java virtual machine used for running applications

Polymorphism. Introduction to Java: History of Java, Java features and advantages, creating classes with Java, Concept of Constructors, Using JDK, Java application and

The proposed algorithm com- bines a simulated annealing schedule specially designed for feature subset selection with the incrementally com- puted joint entropy, reusing previous

Java Script Fundamental: Introduction to Java Script Working with Variables and Data Functions, Meth- ods and Events, Controlling Programming Flow.. The Java Script Object Model

Lebedev Physical Institute, Moscow, Russia 43: Also at California Institute of Technology, Pasadena, USA 44: Also at Budker Institute of Nuclear Physics, Novosibirsk, Russia 45: Also

A Hardware Implementation of the Java Virtual Machine A Hardware Implementation.. of the Java