data types: a data type is a scheme for representing values. an example is int which is the integer,...

229
Data types: •A data type is a scheme for representing values. An example is int which is the Integer, a data type •Values are not just numbers, but any manner of data that a computer can process. •The data type defines the kind of data that is represented by a variable. •As with the keyword class, Java data types are case sensitive.

Upload: nathaniel-harris

Post on 05-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Data types: •A data type is a scheme for representing values. An example is int which is the Integer, a data type •Values are not just numbers, but any manner of data that a computer can process. •The data type defines the kind of data that is represented by a variable. •As with the keyword class, Java data types are case sensitive.

Page 2: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

There are two types of data types primitive data type non-pimitive data type

In primitive data types, there are two categories numeric means Integer, Floating points Non-numeric means Character and Boolean

In non-pimitive types, there are three categories classes arrays interface

Page 3: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Following table shows the datatypes with their size and ranges. Data type Size (byte) Range byte 1 -128 to 127 boolean 1 True or false char 2 A-Z,a-z,0-9,etc. short 2 -32768 to 32767 Int 4 (about) -2 million to 2 million long 8 (about) -10E18 to 10E18 float 4 -3.4E38 to 3.4E18 double 8 -1.7E308 to 1.7E308

Page 4: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Integer data type: Integer datatype can hold the numbers (the number can be positive number or negative number). In Java, there are four types of integer as follows: byte short int long

We can make ineger long by adding 'l‘ or 'L‘ at the end of the number.

Page 5: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Floating point data type:

It is also called as Real number and when we require accuracy then we can use it. There are two types of floating point data type.

float double It is represent single and double precision numbers. The float type is used for single precision and it uses 4 bytes for storage space. It is very useful when we require accuracy with small degree of precision. But in double type, it is used for double precision and uses 8 bytes of starage space. It is useful for large degree of precision.

Page 6: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Character data type: It is used to store single character in memory. It uses 2 bytes storage space.

Boolean data type: It is used when we want to test a particular condition during the excution of the program. There are only two values that a boolean type can hold: true and false. Boolean type is denoted by the keyword boolean and uses only one bit of storage.

Page 7: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Following program shows the use of datatypes. Program: import java.io.DataInputStream; class cc2 { public static void main(String args[]) throws Exception { DataInputStream s1=new DataInputStream(System.in); byte rollno; int marks1,marks2,marks3; float avg; System.out.println("Enter roll number:"); rollno=Byte.parseByte(s1.readLine());

Page 8: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

System.out.println("Enter marks m1, m2,m3:"); marks1=Integer.parseInt(s1.readLine()); marks2=Integer.parseInt(s1.readLine()); marks3=Integer.parseInt(s1.readLine()); avg = (marks1+marks2+marks3)/3; System.out.println("Roll number is="+rollno); System.out.println("Average is="+avg); } } Output: C:\cc>java cc2 Enter roll number: 07 Enter marks m1, m2,m3: 66 77 88 Roll number is=7 Average is=77.0

Page 9: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Mixing Data types: Java allows mixing of constants and variables of different types in an expression, but during assessment it hold to very strict rules of type conversion.

When computer consider operand and operator and if operands are different types then type is automatically convert in higher type. Following table shows the automatic type conversion.

char byte short int long float double

Char int int int int long float double

Byte int int int int long float double

Short int int int int long float double

Int int int int int long float double

Long long long long long long float double

Float float float float float float float double

double double double double double double double double

Page 10: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Variables: Variables are labels that express a particular position in memory and connect it with a data type. The first way to declare a variable: This specifies its data type, and reserves memory for it. It assigns zero to primitive types and null to objects. dataType variableName; The second way to declare a variable: This specifies its data type, reserves memory for it, and puts an initial value into that memory. The initial value must be of the correct data type. dataType variableName = initialValue; The first way to declare two variables: all of the same data type, reserves memory for each. dataType variableNameOne, variableNameTwo; The second way to declare two variables: both of the same data type, reserves memory, and puts an initial value in each variable.

dataType variableNameI = initialValueI, variableNameII=initialValueII;

Page 11: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Variable name:

•Use only the characters 'a‘ through 'z‘, 'A‘ through 'Z‘, '0‘ through '9‘, character '_‘, and character '$‘.

•A name cannot include the space character.

•Do not begin with a digit.

•A name can be of any realistic length.

•Upper and lower case count as different characters.

•A name cannot be a reserved word (keyword).

•A name must not previously be in utilized in this block of the program.

Page 12: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Constant: Constant means fixed value which is not change at the time of execution of program. In Java, there are two types of constant as follows:

Numeric Constants Integer constant Real constant

Character Constants Character constant String constant

Page 13: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Integer Constant: An Integer constant refers to a series of digits. There are three types of integer as follows: a)Decimal integer

Embedded spaces, commas and characters are not alloed in between digits. For example: 23 411 7,00,000 17.33

b) Octal integer

It allows us any sequence of numbers or digits from 0 to 7 with leading 0 and it is called as Octal integer. For example: 011 00 0425

Page 14: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

c) Hexadecimal integer It allows the sequence which is preceded by 0X or 0x and it also allows alphabets from 'A‘ to 'F‘ or 'a‘ to 'f‘ ('A‘ to 'F‘ stands for the numbers '10‘ to '15‘) it is called as Hexadecimal integer. For example: 0x7 00X 0A2B

Real Constant It allows us fractional data and it is also called as folating point constant. It is used for percentage, height and so on. For example: 0.0234 0.777 -1.23

Page 15: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Character Constant It allows us single character within pair of single coute. For example: 'A‘ '7‘ '\‘

String Constant It allows us the series of characters within pair of double coute. For example: “WELCOME”“END OF PROGRAM”“BYE …BYE” “A”

Page 16: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Symbolic constant: In Java program, there are many things which is requires repeatedly and if we want to make changes then we have to make these changes in whole program where this variable is used.

For this purpose, Java provides ‘final‘ keyword to declare the value of variable as follows:

Syntax: final type Symbolic_name=value; For example: If I want to declare the value of ‘PI‘ then: final float PI=3.1459 the condition is, Symbolic_name will be in capital letter( it shows the difference between normal variable and symblic name) and do not declare in method.

Page 17: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Backslash character constant: Java support some special character constant which are given in following table.

Constant Importance

‘\b‘ Back space

‘\t‘ Tab

‘\n‘ New line

‘\\‘ Backslash

‘\” Single coute

‘\”‘ Double coute

Page 18: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Command line arguments:

Command line arguments are parameters that are supplied to the application program at the time of invoking its execution. They must be supplied at the time of its execution following the file name.

In the main () method, the args is confirmed as an array of string known as string objects. Any argument provided in the command line at the time of program execution, are accepted to the array args as its elements. Using index or subscripted entry can access the individual elements of an array. The number of element in the array args can be getting with the length parameter.

Page 19: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

For example: class Add { public static void main(String args[]) { int a=Integer.parseInt(args[0]); int b=Integer.parseInt(args[1]); int c=a+b; System.out.println(―Addition is=‖+c); } } output: c:\javac Add.java c:\java Add 5 2 7

Page 20: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Introduction: A Java program is basically a set of classes. A class is defined by a set of declaration statements and methods or functions. Most statements contain expressions, which express the actions carried out on information or data. Smallest indivisual thing in a program are known as tokens. The compiler recognizes them for building up expression and statements.

Page 21: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Tokens in Java: There are five types of token as follows:

1. Literals 2. Identifiers 3. Operators 4. Separators

Page 22: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Literals: Literals in Java are a sequence of characters (digits, letters and other characters) that characterize constant values to be stored in variables. Java language specifies five major types of literals are as follows: 1. Integer literals 2. Floating point literals 3. Character literals 4. String literals 5. Boolean literals

Page 23: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Identifiers: Identifiers are programmer-created tokens. They are used for naming classes, methods, variables, objects, labels, packages and interfaces in a program. Java identifiers follow the following rules: 1. They can have alphabets, digits, and the underscore and dollar sign characters. 2. They must not start with a digit. 3. Uppercase and lowercase letters are individual. 4. They can be of any length.

Identifier must be meaningful, easily understandable and descriptive. For example: Private and local variables like “length”. Name of public methods and instance variables begin with lowercase letter like “addition”

Page 24: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Keywords: Keywords are important part of Java. Java language has reserved 50 words as keywords. Keywords have specific meaning in Java. We cannot use them as variable, classes and method. Following table shows keywords.

abstract char catch boolean default finally do implements

if long throw private package static break double

this volatile import protected class throws byte else float final public transient

native instanceof case extends int null const new

return try for switch interface void while synchronized

short continue goto super assert const

Page 25: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Operator: Java carries a broad range of operators. An operator is symbols that specify operation to be performed may be certain mathematical and logical operation. Operators are used in programs to operate data and variables. They frequently form a part of mathematical or logical expressions.

Categories of operators are as follows: 1. Arithmetic operators 2. Logical operators 3. Relational operators 4. Assignment operators 5. Conditional operators 6. Increment and decrement operators 7. Bit wise operators

Page 26: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Arithmetic operators: Arithmetic operators are used to make mathematical expressions and the working out as same in algebra. Java provides the fundamental arithmetic operators. These can operate on built in data type of Java. Following table shows the details of operators.

Operator Importance/ significance + Addition - Subtraction / Division * Multiplication % Modulo division or remainder

Page 27: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

“+” operator in Java: In this program, we have to add two integer numbers and display the result. class AdditionInt { public static void main (String args[]) { int a = 6; int b = 3; System.out.println("a = " + a); System.out.println("b =" + b); int c = a + b; System.out.println("Addition = " + c); } } Output: a= 6 b= 3 Addition=9

Page 28: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Logical operators: When we want to form compound conditions by combining two or more relations, then we can use logical operators. Following table shows the details of operators.

Operators Importance/ significance

|| Logical – OR && Logical –AND ! Logical –NOT

The logical expression defer a value of true or false. Following table shows the truth table of Logical – OR and Logical – AND.

Page 29: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Truth table for Logical – OR operator: Operand1 Operand3 Operand1 || Operand3

T T T T F T F T T F F F

T – True F - False Truth table for Logical – AND operator:

Operand1 Operand3 Operand1 && Operand3 T T T T F F F T F F F F

Page 30: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Now the following program shows the use of Logical operators. class LogicalOptr { public static void main (String args[]) { boolean a = true; boolean b = false; System.out.println("a||b = " +(a||b)); System.out.println("a&&b = "+(a&&b)); System.out.println("a! = "+(!a)); } } Output: a||b = true a&&b = false a! = false

Page 31: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Relational Operators: When evaluation of two numbers is performed depending upon their relation, assured decisions are made. The value of relational expression is either true or false. If A=7 and A < 10 is true while 10 < A is false. Following table shows the details of operators.

Operator Importance/ significance > Greater than < Less than

!= Not equal to >= Greater than or equal to <= Less than or equal to

Page 32: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Now, following examples show the actual use of operators. 1) If 10 > 30 then result is false 2) If 40 > 17 then result is true 3) If 10 >= 300 then result is false 4) If 10 <= 10 then result is true

Now the following program shows the use of operators. class Reloptr1 { public static void main (String args[]) { int a = 10; int b = 30;

System.out.println("a>b = " +(a>b)); System.out.println("a<b = "+(a<b)); System.out.println("a<=b = "+(a<=b)); } }

Page 33: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Output: a>b = false a<b = true a<=b = true

Program :class Reloptr3 { public static void main (String args[]) { int a = 10; int b = 30; int c = 30; System.out.println("a>b = " +(a>b)); System.out.println("a<b = "+(a<b)); System.out.println("a<=c = "+(a<=c)); System.out.println("c>b = " +(c>b)); System.out.println("a<c = "+(a<c)); System.out.println("b<=c = "+(b<=c)); } }

Page 34: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Output: a>b = false a<b = true a<=c = true c>b = true a<c = true b<=c = true

Assignment Operators: Assignment Operators is used to assign the value of an expression to a variable and is also called as Shorthand operators.

Variable_name binary operator = expression

Following table show the use of assignment operators.

Page 35: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Simple Assignment Operator

Statement with shorthand Operators

A=A+1 A+=1 A=A-1 A-=1 A=A/(B+1) A/=(B+1) A=A*(B+1) A*=(B+1) A=A/C A/=C A=A%C A%=C

Page 36: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

These operators avoid repetition, easier to read and write. Now the following program shows the use of operators. class Assoptr { public static void main (String args[]) { int a = 10; int b = 30; int c = 30; a+=1; b-=3; c*=7; System.out.println("a = " +a); System.out.println("b = "+b); System.out.println("c = "+c); } } Output: a = 11 b = 18 c = 310

Page 37: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Conditional Operators:

The character pair ?: is a ternary operator of Java, which is used to construct conditional expressions of the following form:

Expression1 ? Expression3 : Expression3

The operator ? :

works as follows:

Expression1 is evaluated if it is true then Expression3 is evaluated and becomes the value of the conditional expression. If Expression1 is false then Expression3 is evaluated and its value becomes the conditional expression.

Page 38: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

For example: A=3; B=4; C=(A<B)?A:B; C=(3<4)?3:4; C=4

Page 39: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Now the following program shows the use of operators. class Coptr { public static void main (String args[]) { int a = 10; int b = 30; int c; c=(a>b)?a:b; System.out.println("c = " +c); c=(a<b)?a:b; System.out.println("c = " +c); } } Output: c = 30 c = 10

Page 40: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

program3:Write a program to check whether number is positive or negative.

class PosNeg { public static void main(String args[]) { int a=10; int flag=(a<0)?0:1; if(flag==1) System.out.println(“Number is positive”); else System.out.println(“Number is negative”); } } Output: Number is positive

Page 41: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Increment and Decrement Operators: The increment operator ++ adds 1 to a variable. Usually the variable is an integer type, but it can be a floating point type. The two plus signs must not be split by any character. Usually they are written immediately next to the variable

Expression Process Example end result A++ Add 1 to a variable

after use. int A=10,B; B=A++;

A=11 B=10

++A Add 1 to a variable before use.

int A=10,B; B=++A;

A=11 B=11

A-- Subtract 1 from a variable after use.

int A=10,B; B=A--;

A=9 B=10

--A Subtract 1 from a variable before use.

int A=10,B; B=--A;

A=9 B=9

Page 42: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

class IncDecOp { public static void main(String args[]) { int x=1; int y=3; int u; int z; u=++y; z=x++; System.out.println(x); System.out.println(y); System.out.println(u); System.out.println(z); } } Output: 3 4 4

1

Page 43: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Bit Wise Operators: Bit wise operator execute single bit of their operands. Following table shows bit wise operator:

Operator Importance/ significance

| Bitwise OR

& Bitwise AND

&= Bitwise AND assignment

|= Bitwise OR assignment

^ Bitwise Exclusive OR

<< Left shift

>> Right shift

~ One‘s complement

Page 44: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Now the following program shows the use of operators. (1) Program 1

class Boptr1 { public static void main (String args[]) { int a = 4; int b = a<<3; System.out.println("a = " +a); System.out.println("b = " +b); } } Output: a =4 b =16

Page 45: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Program 3 Class Boptr3 { public static void main (String args[]) { int a = 16; int b = a>>3; System.out.println("a = " +a); System.out.println("b = " +b); } } Output: a = 16 b = 3

356 138 64 33 16 8 4 3 1 38 37 36 35 34 33 33 31 30

Page 46: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Separator: Separators are symbols. It shows the separated code.they describe function of our code.

Name Use

() Parameter in method definition, containing statements for conditions,etc.

{} It is used for define a code for method and classes

[] It is used for declaration of array

; It is used to show the separate statement

, It is used to show the separation in identifier in variable declarartion

. It is used to show the separate package name from sub-packages and classes, separate variable and method from reference variable.

Page 47: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Operator Precedence in Java: An arithmetic expression without any parentheses will be calculated from left to right using the rules of precedence of operators. There are two priority levels of arithmetic operators are as follows: (a) High priority (* / %) (b) Low priority (+ -)

The evaluation process includes two left to right passes through the expression. During the first pass, the high priority operators are applied as they are encountered. During the second pass, the low priority operators are applied as they are encountered.

Page 48: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Operator Associativity Rank [ ] Left to right 1 ( ) Left to right

2

. Left to right - Right to left

++ Right to left -- Right to left ! Right to left ~ Right to left

(type) Right to left * Left to right

3 / Left to right % Left to right + Left to right

4 - Left to right

<< Left to right 5 >> Left to right

>>> Left to right < Left to right

6 <= Left to right > Left to right

>= Left to right Instanceof Left to right

== Left to right 7

!= Left to right & Left to right 8 ^ Left to right 9 | Left to right 10

&& Left to right 11 || Left to right 12 ?: Right to left 13 = Right to left 14

Page 49: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Control Structure

In java program, control structure is can divide in three parts: Selection statement Iteration statement Jumps in statement

Selection Statement: Selection statement is also called as Decision making statements because it provides the decision making capabilities to the statements. In selection statement, there are two types: if statement switch statement

These two statements are allows you to control the flow of a program with their conditions.

Page 50: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

if Statement: The “if statement” is also called as conditional branch statement. It is used to program execution through two paths. The syntax of “if statement” is as follows:

Syntax: if (condition) { Statement 1; Statement 2; ... } else { Statement 3; Statement 4; ... }

Page 51: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

The “if statement” is a commanding decision making statement and is used to manage the flow of execution of statements. The “if statement” is the simplest one in decision statements. Above syntax is shows two ways decision statement and is used in combination with statements. Following figure shows the “if statement”

true

Condition ?

false

Page 52: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Simple if statement:

Syntax:

If (condition) { Statement block; } Statement-a;

In statement block, there may be single statement or multiple statements. If the condition is true then statement block will be executed. If the condition is false then statement block will omit and statement-a will be executed.

Page 53: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

The if…else statement: Syntax: If (condition) { True - Statement block; } else { False - Statement block; } Statement-a; If the condition is true then True - statement block will be executed. If the condition is false then False - statement block will be executed. In both cases the statement-a will always executed.

Page 54: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Following figure shows the flow of statement.

True –

Statement

Block

False –

Statement

Block

Statement ‘a’

Condition?

Page 55: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Following program shows the use of if statement. Program: write a program to check whether the number is positive or negative. import java.io.*; class NumTest { public static void main (String[] args) throws IOException { int Result=11; System.out.println("Number is"+Result); if ( Result < 0 ) { System.out.println("The number "+ Result +" is negative"); } else { System.out.println("The number "+ Result +" is positive"); } System.out.println("------- * ---------"); } }

Page 56: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Output:C:\cse>java NumTest Number is 11 The number 11 is positive ------- * ---------

(All conditional statements in Java require boolean values, and that's what the ==, <, >, <=, and >= operators all return. A boolean is a value that is either true or false. If you need to set a boolean variable in a Java program, you have to use the constants true and false. Boolean values are no more integers than are strings).

Page 57: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

write a program to check whether the number is divisible by 2 or not. import java.io.*; class divisorDemo { public static void main(String[] args) { int a =11; if(a%2==0) { System.out.println(a +" is divisible by 2"); } else { System.out.println(a+" is not divisible by 2"); } } } Output: C:\cse>java divisorDemo 11 is not divisible by 2

Page 58: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Nesting of if-else statement: Syntax: if (condition1) { If(condition2) { Statement block1; } else { Statement block2; } } else { Statement block3; } Statement 4;

Page 59: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

If the condition1 is true then it will be goes for condition2. If the condition2 is true then statement block1 will be executed otherwise statement2 will be executed. If the condition1 is false then statement block3 will be executed. In both cases the statement4 will always executed.

Statement3 Statement2 Statement1

Statement4

Condition1

Condition2

false

false

true

true

Page 60: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Write a program to find out greatest number from three numbers. class greatest { public static void main(String args[]) { int a=10; int b=20; int c=3; if(a>b) { if(a>c) { System.out.println("a is greater number"); } else { System.out.println("c is greater number"); } }

Page 61: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

else { if(c>b) { System.out.println("c is greater number"); } else { System.out.println("b is greater number"); } } } } Output: C:\CSE>java greatest b is greater number

Page 62: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

switch statement: In Java, switch statement check the value of given variable or statement against a list of case values and when the match is found a statement-block of that case is executed. Switch statement is also called as multiway decision statement. Syntax: switch(condition)// condition means case value { case value-1:statement block1;break; case value-2:statement block2;break; case value-3:statement block3;break; … default:statement block-default;break; } statement a;

Page 63: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

The condition is byte, short, character or an integer. value-1,value-2,value-3,…are constant and is called as labels. Each of these values be matchless or unique with the statement. Statement block1, Statement block2, Statement block3,..are list of statements which contain one statement or more than one statements. Case label is always end with “:” (colon).

Page 64: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Program:write a program for bank account to perform following operations. -Check balance -withdraw amount -deposit amount

For example: import java.io.*; class bankac { public static void main(String args[]) throws Exception { int bal=20000; int ch=Integer.parseInt(args[0]); System.out.println("Menu"); System.out.println("1:check balance"); System.out.println("2:withdraw amount... plz enter choice and amount"); System.out.println("3:deposit amount... plz enter choice and amount"); System.out.println("4:exit");

Page 65: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

switch(ch) { case 1:System.out.println("Balance is:"+bal); break; case 2:int w=Integer.parseInt(args[1]); if(w>bal) { System.out.println("Not sufficient balance"); } bal=bal-w; System.out.println("Balance is"+bal); break; case 3:int d=Integer.parseInt(args[1]); bal=bal+d; System.out.println("Balance is"+bal); break; default:break; } } }

Page 66: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Output: C:\CSE>javac bankac.java C:\CSE>java bankac 1 Menu 1:check balance 2:withdraw amount... plz enter choice and amount 3:deposit amount... plz enter choice and amount 4:exit Balance is:20000 C:\CSE>java bankac 2 2000 Menu 1:check balance 2:withdraw amount... plz enter choice and amount 3:deposit amount... plz enter choice and amount 4:exit Balance is18000

Page 67: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

C:\CSE>java bankac 3 2000 Menu 1:check balance 2:withdraw amount... plz enter choice and amount 3:deposit amount... plz enter choice and amount 4:exit Balance is22000 C:\CSE>java bankac 4 Menu 1:check balance 2:withdraw amount... plz enter choice and amount 3:deposit amount... plz enter choice and amount 4:exit C:\CSE>java bankac

Page 68: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Iteration Statement: The process of repeatedly executing a statements and is called as looping. The statements may be executed multiple times (from zero to infinite number). If a loop executing continuous then it is called as Infinite loop. Looping is also called as iterations.

In Iteration statement, there are three types of operation:

•for loop •while loop •do-while loop

Page 69: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

for loop: The for loop is entry controlled loop. It means that it provide a more concious loop control structure.

Syntax: for(initialization;condition;iteration)//iteration means increment/decrement

{ Statement block; }

Page 70: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

import java.io.*; class number { public static void main(String args[]) throws Exception { int i; System.out.println("list of 1 to 10 numbers"); for(i=1;i<=10;i++) { System.out.println(i); } } }

Page 71: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Output: C:\CSE>javac number.java C:\CSE>java number list of 1 to 10 numbers 1 2 3 4 5 6 7 8 9 10

Page 72: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

while loop: The while loop is entry controlled loop statement. The condition is evaluated, if the condition is true then the block of statements or statement block is executed otherwise the block of statement is not executed.

Syntax: While(condition) { Statement block; }

Page 73: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

example:Write a program to display 1 to 10 numbers using while loop. import java.io.*; class number { public static void main(String args[]) throws Exception { int i=1; System.out.println("list of 1 to 10 numbers"); while(i<=10) { System.out.println(i); i++; } } }

Page 74: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Output: C:\CSE>javac number.java C:\CSE>java number list of 1 to 10 numbers 1 2 3 4 5 6 7 8 9 10

Page 75: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

do-while loop: In do-while loop, first attempt of loop should be execute then it check the condition.

The benefit of do-while loop/statement is that we get entry in loop and then condition will check for very first time. In while loop, condition will check first and if condition will not satisfied then the loop will not execute.

Syntax: do { Statement block; } While(condition);

In program, when we use the do-while loop, then in very first attempt, it allows us to get enter in loop and execute that loop and then check the condition.

Page 76: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Write a program to display 1 to 10 numbers using do-while loop.

import java.io.*;

class number { public static void main(String args[]) throws Exception { int i=1; System.out.println("list of 1 to 10 numbers"); do { System.out.println(i); i++; }while(i<=10); } }

Page 77: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Output: C:\CSE>javac number.java C:\CSE>java number list of 1 to 10 numbers 1 2 3 4 5 6 7 8 9 10

Page 78: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Jumps in statement: Statements or loops perform a set of operartions continually until the control variable will not satisfy the condition. but if we want to break the loop when condition will satisy then Java give a permission to jump from one statement to end of loop or beginning of loop as well as jump out of a loop.

“break” keyword use for exiting from loop and “continue” keyword use for continuing the loop.

Following statements shows the exiting from loop by using “break” statement.

Page 79: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

do-while loop: do { ……………… ……………… if(condition) { break;//exit from if loop and do-while loop } …………….. …………….. } While(condition); ……….. ………..

Page 80: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

For loop: for(…………) { …………… ………….. if(…………..) break; ;//exit from if loop and for loop …………… …………… } …………… ………….. While loop: while(…………) { …………… ………….. if(…………..) break; ;//exit from if loop and while loop …………… …………… }

Page 81: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Following statements shows the continuing the loop by using “continue” statement. do-while loop: do { ……………… ……………… if(condition) { continue;//continue the do-while loop } …………….. …………….. } While(condition); ……….. ………..

Page 82: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

For loop: for(…………) { …………… ………….. if(…………..) continue ;// continue the for loop …………… …………… } …………… …………..

Page 83: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

While loop: while(…………) { …………… ………….. if(…………..) continue ;// continue the while loop …………… …………… } ……………. …………….

Page 84: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Labelled loop: We can give label to a block of statements with any valid name.following example shows the use of label, break and continue. For example: Import java.io.*; class Demo { public static void main(String args[]) throws Exception { int j,i;

Page 85: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

LOOP1: for(i=1;i<100;i++) { System.out.println(““); if(i>=10) { break; } for(j=1;j<100;j++) { System.out.println(“$ ”); if(i==j) { continue LOOP1; } } }

System.out.println(“ End of program “); } }

Page 86: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Output: $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ End of program

Page 87: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

8787

INTRODUCTION TO ARRAYS

The following variable declarations each allocate enough storage to hold one value of the specified data type.

int number;

double income;

char letter;

Page 88: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

8888

• An array is an object containing a list of elements of the same data type.

Page 89: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

8989

• We can create an array by:– Declaring an array reference variable to store the address of an

array object.– Creating an array object using the new operator and assigning the

address of the array to the array reference variable.

Page 90: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9090

Here is a statement that declares an array reference variable named dailySales: double[ ] dailySales;

The brackets after the key word double indicate that the variable is an array reference variable. This variable can hold the address of an array of values of type double. We say the data type of dailySales is double array reference.

Page 91: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9191

The second statement of the segment below creates an arrayobject that can store seven values of type double and assigns the address of the array object to the reference variable nameddailySales:

double[ ] dailySales;

dailySales = new double[7];

• The operand of the new operator is the data type of the individual array elements and a bracketed value that is the array size declarator.

• The array size declarator specifies the number of elements in the

array.

Page 92: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9292

• It is possible to declare an array reference variable and create the array object it references in a single statement.

Here is an example:

double[ ] dailySales = new double[7];

Page 93: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9393

The statement below creates a reference variable named dailySales and an array object that can store seven values of type double as illustrated below:

double[ ] dailySales = new double[7];

addressdailySales

1st value 2nd value 3rd value 4th value 5th value 6th value 7th value

Page 94: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9494

• Arrays can be created to store values of any data type.

The following are valid Java statements that create arrays that store values of various data types:

double[ ] measurements = new double[24];

char[ ] ratings = new char[100];

int[ ] points = new int[4];

Page 95: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9595

• The array size declarator must be an integer expression with a value greater than zero.

Page 96: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9696

• It is common to use a named constant as the array size declarator and then use this named constant whenever you write statements that refer to the size of the array. This makes it easier to maintain and modify the code that works with an array.

The statements below define a named constant called MAX_STUDENTS and an array with room for one hundred elements of type int that is referenced by a variable named testScores.

final int MAX_STUDENTS = 100;

int[ ] testScores = new int[MAX_STUDENTS];

Page 97: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9797

• We can access the array elements and use them like individual variables.

• Each array element has a subscript. This subscript can be used to select/pinpoint a particular element in the array.

• Array subscripts are offsets from the first array element. • The first array element is at offset/subscript 0, the second

array element is at offset/subscript 1, and so on.• The subscript of the last element in the array is one less

than the number of elements in the array.

Accessing Array Elements

Page 98: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9898

final int DAYS = 7;

double[ ] dailySales = new double[DAYS];

dailySales[0], pronounced dailySales sub zero, is the first element of the array.dailySales[1], pronounced dailySales sub one, is the second element of the array.dailySales[6], pronounced dailySales sub six, is the last element of the array.

0 0 0 0 0 0 0[0] [1] [2] [3] [4] [5] [6]

addressdailySales

Subscripts

Page 99: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

9999

• Array subscripts begin with zero and go up to n - 1, where n is the number of elements in the array.

final int DAYS = 7;

double[ ] dailySales = new double[DAYS];

0 0 0 0 0 0 0[0] [1] [2] [3] [4] [5] [6]

addressdailySales

Subscripts

Page 100: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

100100

• The value inside the brackets when the array is created is the array size declarator.

• The value inside the brackets of any other statement that works with the contents of an array is the array subscript.

Page 101: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

101101

• Each element of an array, when accessed by its subscript, can be used like an individual variable.

The individual elements of the dailySales array are variables of type double, we can write statements like the following:

final int DAYS = 7;

double[ ] dailySales = new double[DAYS];

dailySales[0] = 9250.56; // Assigns 9250.56 to dailySales sub zero

dailySales[6] = 11943.78; // Assigns 11943.78 to the last element of the array

Page 102: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

102102

final int DAYS = 7;

double[ ] dailySales = new double[DAYS];

dailySales[0] = 9250.56; // Assigns 9250.56 to dailySales sub zerodailySales[6] = 11943.78; // Assigns 11943.78 to the last element of the arraySystem.out.print("Enter the daily sales for Monday: ");

dailySales[1] = keyboard.nextDouble( ); // Stores the value entered in dailySales sub 1

double sum = dailySales[0] + dailySales[1]; // Adds the values of the first two elements

System.out.println("The sum of the daily sales for Sunday and Monday are " +

sum + ".");

System.out.println("The sales for Monday were: " + dailySales[1]);

9250.56 ???? 0 0 0 0 11943.78[0] [1] [2] [3] [4] [5] [6]

addressdailySales

Subscripts

Page 103: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

103103

INTRODUCTION TO ARRAYSAccessing Array Elements

• The values stored in the array must be accessed via the array subscripts.

Page 104: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

104104

The last statement in the segment below produces a logical error. The value of dailySales is the address where the array object is stored. This address is displayed in hexidecimal.

final int DAYS = 7;

double[ ] dailySales = new double[DAYS];

dailySales[0] = 9250.56; // Assigns 9250.56 to dailySales sub zero

dailySales[6] = 11943.78; // Assigns 11943.78 to the last element of the array

System.out.print("Enter the daily sales for Monday: ");

dailySales[1] = keyboard.nextDouble( ); // Stores the value entered in dailySales sub 1

System.out.println("The daily sales for each day of the week were " + dailySales); // Error

Page 105: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

105105

• Subscript numbers can be stored in variables. • Typically, we use a loop to cycle through all the subscripts

in the array to process the data in the array.

Page 106: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

106106

• Java performs bounds checking, which means it does not allow a statement to use a subscript that is outside the range 0 through n - 1, where n is the value of the array size declarator.

Java Performs Bounds Checking

Page 107: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

107107

The valid subscripts in the array referenced by dailySales are 0 through 6. Java will not allow a statement that uses a subscript less than 0 or greater than 6. Notice the correct loop header in the segment below:

final int DAYS = 7;

int counter;

double[ ] dailySales = new double[DAYS];

for (counter = 0; counter < DAYS; counter++){

System.out.print("Enter the sales for day " + (counter + 1) + ": ");

dailySales[counter] = keyboard.nextDouble( );

}

Page 108: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

108108

• Java does its bounds checking at runtime.• The compiler does not display an error message when it

processes a statement that uses an invalid subscript.• Instead, Java throws an exception and terminates the program

when a statement is executed that uses a subscript outside the array bounds. This is not something you want the user of your program to encounter, so be careful when constructing a loop that cycles through the subscripts of an array.

Page 109: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

109109

• Like other variables, you may give array elements an initial value when creating the array.

Example:

The statement below declares a reference variable named temperatures, creates an array object with room for exactly tens values of type double, and initializes the array to contain the values specified in the initialization list.

double[ ] temperatures = {98.6, 112.3, 99.5, 96, 96.7, 32, 39, 18.1, 99, 111.5};

Array Initialization

Page 110: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

110110

• A series comma-separated values inside braces is an initialization list.

• The values specified are stored in the array in the order in which they appear.

• Java determines the size of the array from the number of elements in the initialization list.

double[ ] temperatures = {98.6, 112.3, 99.5, 96, 96.7, 32, 39, 18.1, 99, 111.5};

98.6 112.3 99.5 96.0 96.7 32.0 39.0 18.1 99.0 111.5[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

addresstemperatures

Page 111: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

111111

• By default, Java initializes the array elements of a numeric array with the value 0.

int[ ] attendance = new int[5] ;

0 0 0 0 0[0] [1] [2] [3] [4]

addressattendance

Page 112: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

112112

• Each array object has an attribute/field named length. This attribute contains the number of elements in the array.

For example, in the segment below the variable named size is assigned the value 5, since the array referenced by values has 5 elements.

int size;

int[ ] values = {13, 21, 201, 3, 43};

size = values.length;Notice, length is an

attribute of an array not a method - hence no

parentheses.

Array Length

Page 113: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

113113

To display the elements of the array referenced by values, we could write:

int count;

int[ ] values = {13, 21, 201, 3, 43};

for (count = 0; count < values.length; count++)

{System.out.println("Value #" + (count + 1) + " in the list of values is "

+ values[count]);

}

Notice, the valid subscripts are zero

through values.length - 1.

Page 114: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

114114

• The assignment operator does not copy the contents of one array to another array.

Reassigning Array Reference Variables

Page 115: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

115115

The third statement in the segment below copies the address stored in oldValues to the reference variable named newValues. It does not make a copy of the contents of the array referenced by oldValues.

short[ ] oldValues = {10, 100, 200, 300};

short[ ] newValues = new short[4];

newValues = oldValues; // Does not make a copy of the contents of the array ref. // by oldValues

Page 116: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

116116

After the following statements execute, we have the situation illustrated below:

short[ ] oldValues = {10, 100, 200, 300};

short[ ] newValues = new short[4];

When the assignment statement below executes we will have:

newValues = oldValues; // Copies the address in oldValues into newValues

10 100 200 300[0] [1] [2] [3]

0 0 0 0[0] [1] [2] [3]

addressoldValues

addressnewValues

10 100 200 300[0] [1] [2] [3]

addressoldValues

addressnewValues

Reassigning Array Reference Variables

Page 117: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

117117

• To copy the contents of one array to another you must copy the individual array elements.

Copying The Contents of One Array to Another Array

Page 118: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

118118

To copy the contents of the array referenced by oldValues to the array referenced by newValues we could write:

int count;

short[ ] oldValues = {10, 100, 200, 300};short[ ] newValues = new short[4];

// If newValues is large enough to hold the values in oldValues

if (newValues.length >= oldValues.length) {

for (count = 0; count < oldValues.length; count++){

newValues[count] = oldValues[count];}

}

Page 119: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

119119

• An array can be passed as an argument to a method. • To pass an array as an argument you include the name of

the variable that references the array in the method call. • The parameter variable that receives the array must be

declared as an array reference variable.

PASSING AN ARRAY AS AN ARGUMENT TO A METHOD

Page 120: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

120120

• When an array is passed as an argument, the memory address stored in the array reference variable is passed into the method.

• The parameter variable that stores this address references the array that was the argument.

• The method does not get a copy of the array. • The method has access to the actual array that was the

argument and can modify the contents of the array.

Page 121: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

121121

SOME USEFUL ARRAY OPERATIONSComparing Arrays

The decision in the segment below does not correctly determine if the contents of the two arrays are the same.

char[ ] array1 = {'A', 'B', 'C', 'D', 'A'};

char[ ] array2 = {'A', 'B', 'C', 'D', 'A'};

boolean equal = false;

if (array1 == array2) // This is a logical error

{

equal = true;

}

Page 122: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

122122

SOME USEFUL ARRAY OPERATIONSComparing Arrays

We are comparing the addresses stored in the reference variables array1 and array2. The two arrays are not stored in the same memory location so the conditional expression is false and the value of equal stays at false.

char[ ] array1 = {'A', 'B', 'C', 'D', 'A'};char[ ] array2 = {'A', 'B', 'C', 'D', 'A'};boolean equal = false;

if (array1 == array2) // This is false - the addresses are not equal{

equal = true;}

Page 123: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

123123

• To compare the contents of two arrays, you must compare the individual elements of the arrays.

• Write a loop that goes through the subscripts of the arrays comparing the elements at the same subscript/offset in the two arrays.

Page 124: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

124124

public static boolean equals(char[ ] firstArray, char[ ] secArray){

int subscript;boolean sameSoFar = true;

if (firstArray.length != secArray.length){

sameSoFar = false;}

subscript = 0;

while (sameSoFar && subscript < firstArray.length){

if (firstArray[subscript] != secArray[subscript]){sameSoFar = false;}

subscript++; // Incr. the counter used to move through the subscripts}return sameSoFar;

}

Page 125: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

125125

SOME USEFUL ARRAY OPERATIONS Finding the Sum of the Values in a Numeric Array

• To find the sum of the values in a numeric array, create a loop to cycle through all the elements of the array adding the value in each array element to an accumulator variable that was initialized to zero before the loop.

Page 126: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

126126

SOME USEFUL ARRAY OPERATIONS Finding the Sum of the Values in a Numeric Array

/** A method that finds and returns the sum of the values in the array of ints that is passed into the method. @param array The array of ints @return The double value that is the sum of the values in the array.*/

public static double getSum(int[ ] array){

int offset; // Loop counter used to cycle through all the subscripts in the arraydouble sum; // The accumulator variable - it is initialized in the header below

for (sum = 0, offset = 0; offset < array.length; offset++){

sum += array[offset];}

return sum;}

Page 127: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

127127

SOME USEFUL ARRAY OPERATIONS Finding the Average of the Values in a Numeric Array

• To find the average of the values in a numeric array, first find the sum of the values in the array. Then divide this sum by the number of elements in the array.

Page 128: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

128128

SOME USEFUL ARRAY OPERATIONSFinding the Average of the Values in a Numeric Array

/** A method that finds and returns the average of the values in the array of ints that is passed into the method. @param array The array of ints @return The double value that is the average of the values in the array.*/

public static double getAverage(int[ ] array){

int offset; // Loop counter used to cycle through all the subscripts in the arraydouble sum; // The accumulator variable - it is initialized in the header belowdouble average;

for (sum = 0, offset = 0; offset < array.length; offset++){

sum += array[offset];}average = sum / array.length;

return average;}

Page 129: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

129129

SOME USEFUL ARRAY OPERATIONS Finding the Highest and Lowest Values in a Numeric Array

• To find the highest value in a numeric array, copy the value of the first element of the array into a variable called highest. This variable holds a copy of the highest value encountered so far in the array.

• Loop through the subscripts of each of the other elements of the array. Compare each element to the value currently in highest. If the value of the element is higher than the value in highest, replace the value in highest with the value of the element.

• When the loop is finished, highest contains a copy of the highest value in the array.

Page 130: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

130130

SOME USEFUL ARRAY OPERATIONSFinding the Highest and Lowest Values in a Numeric Array

/**A method that finds and returns the highest value in an array of doubles. @param array An array of doubles @return The double value that was the highest value in the array.*/

public static double getHighest(double[ ] array){

int subscript;

double highest = array[0];

for (subscript = 1; subscript < array.length; subscript++){

if (array[subscript] > highest){highest = array[subscript];}

}return highest;

}

Page 131: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

131131

SOME USEFUL ARRAY OPERATIONSFinding the Highest and Lowest Values in a Numeric Array

• The lowest value in an array can be found using a method that is very similar to the one for finding the highest value.

• Keep a copy of the lowest value encountered so far in the array in a variable, say lowest.

• Compare the value of each element of the array with the current value of lowest. If the value of the element is less than the value in lowest, replace the value in lowest with the value of the element.

• When the loop is finished, lowest contains a copy of the lowest value in the array.

Page 132: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

132132

WORKING WITH PARTIALLY FILLED ARRAYS

• Quite often we do not know the exact number of items that we will need to store when we write a program. When this is the case, we can create an array that is large enough to hold the largest possible number of items and keep track of the actual number of items stored in the array.

• If the actual number of items stored in the array is less than the number of elements, we say that the array is partially filled.

• When you process the items in a partially filled array you only want to process array elements that contain valid data items.

• Keep a count of the actual number of items in the array in an integer variable as the array is filled and use this value as the upper bound on the array subscripts when processing the contents of the array.

Page 133: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

133133

WORKING WITH PARTIALLY FILLED ARRAYS

Suppose we wanted to get up to one hundred whole numbers from the user and store them in an array and then do some processing on the contents of the array.

*** See the program PartiallyFilledArray.java on webct

Page 134: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

134134

WORKING WITH PARTIALLY FILLED ARRAYS

Notice that it is not necessary, actually, it is wasteful to use an array to get the functionality produced by the program PartiallyFilledArray.java. We could instead add each number to an accumulator as we read it and keep a count of the valid numbers read and added to the accumulator. After all the numbers are read we can calculate and display the average.

Page 135: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

135135

RETURNING AN ARRAY FROM A METHOD

• A method can return an array to the statement that made the method call. Actually, it is a reference to the array (the address of the array) that is returned.

• When a method returns an array reference, the return type of the method must be specified as an array reference.

• Return the address of an array from a method by putting the name of the variable that references the array after the key word return at the end of the method.

Page 136: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

136136

RETURNING AN ARRAY FROM A METHOD

/**A method that gets ten whole numbers from the user and stores them in an array and returns the reference to the array to the calling method. @return The array containing the integers entered by the user*/

public static int[ ] getArrayOfInts( ){

Scanner keyboard = new Scanner(System.in);

final int MAX_NUMBERS = 10;int[ ] numbers = new int[MAX_NUMBERS];int subscript;

for (subscript = 0; subscript < numbers.length; subscript++){

System.out.print("Enter number " + (subscript + 1) + ": ");numbers[subscript] = keyboard.nextInt( );

}return numbers;

} // End of the method getArrayOfInts

Page 137: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

VISIBILITY CONTROL IN JAVA

Page 138: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

ACCESS MODIFIERS

• Visibility modifiers also known as access modifiers can be applied to the instance variables and methods within a class.

• Java provides the following access modifiers

Public Friendly/Package (default)

Private Protected

Page 139: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

PUBLIC ACCESS

• Any variable or method is visible to the entire class in which it is defined.

• What is we want to make it visible to all classes outside the current class??

• This is possible by simply declaring the variable as ‘public’

• When no access modifier member defaults to a limited version of public accessibility known as ‘friendly’ level of access. This is also known as package access.

FRIENDLY ACCESS

Page 140: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

• So what is the difference between the public and the friendly access???

• The difference between the public and the friendly access is that public modifier makes the field visible in all classes regardless of their package while the friendly access make them visible only within the current package and not within the other packages.

Page 141: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

PROTECTED ACCESS

• The visibility level of the protected field lies between the private and the package access.

• That is the protected access makes the field visible not only to all classes and subclasses in the same package but also to subclasses in other package

• Non subclasses in their packages cannot access the protected members

• Enjoys high degree of protection.• They are accessible only within their own class• They cannot be inherited by their subclass and hence not

visible in it.

PRIVATE ACCESS

Page 142: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Public Protected Friendly Private

Same class Yes Yes Yes Yes

Subclass in same package Yes Yes Yes No

Other classes in same package Yes Yes Yes No

Subclasses in other package Yes Yes No No

Non subclasses in other package Yes No No No

AccessModifier

AccessLocation

Page 143: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

The Java Console

• The console or console screen is a screen where the input and output is simple text.– This is a term from the days when computer

terminals were only text input and output.– Now when using the console for output, it is said

that you are using the standard output device. • Thus when you print to the console, you are using

standard output.

• In Java, you can write to the console, using the methods included in the Java API.

Page 144: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Java API• The Java Application Programmer Interface (API) is a

standard library of prewritten classes for performing specific operations.– These classes are available to all Java programs.

• There are TONS of classes in the Java API. That do MANY different tasks.

• If you want to perform an operation, try either Googling it before implementing it from scratch.– Often you will get a link to the Java API that will reference the

class and method/data attribute you need.– Example: “Java Round”– Other times, you will get an example– Example: “Java Ceiling”

Page 145: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Print and Println• Like stated before, you can perform output to the Java console using the

Java API.• Two methods to do this are print, and println.

– print – print some text to the screen– println – print some text to the screen and add a new line character at the

end (go to the next line).– These two methods are methods in the out class, which itself is contained in

the System class.• This creates a hierarchy of objects.• System has member objects and methods for performing system level operations (such

as sending output to the console)• out is a member of the System class and provides methods for sending output to the

screen.• System, out, print, and println are all in the Java API.• Because of this relationship of objects, something as simple as printing to

the screen is a relatively long line of code.• We’ve seen this before…

Page 146: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

System.out.println(“Hello World!”);• The dot operator here tells the compiler that we are going to use

something inside of the class/object preceding it.• So System.out says that we are using the out object in the

System class.• The text displayed is inside of the parentheses.

– This is called an argument• We will talk more about arguments when we go over functions, but for now,

just know that whatever is in the parentheses will be printed to the console for the print and println methods.

• The argument is inside of double quotes, this makes it a string literal.– A String is a type in Java that refers to a series of characters

• We will go over literals, types, and strings later

Dissecting println

Page 147: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Console Output Examples 1 & 2

• New Topics:– print– println

Page 148: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Escape Sequences• What would be the problem with this?:System.out.println("He said "Hello" to me");

• The compiler does not know that the "s aren’t ending and starting a new string literal.

• But, we want double quotes in our string…How do we fix this?– Answer: Escape Sequences

• Escape Sequences allow a programmer to embed control characters or reserved characters into a string. In Java they begin with a backslash and then are followed by a character.

• Control Characters are characters that either cannot be typed with a keyboard, but are used to control how the string is output on the screen.

• Reserved Characters are characters that have special meaning in a programming language and can only be used for that purpose.

Page 149: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

IO StreamJava performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output without having every part of your code understand the physical.

Java encapsulates Stream under java.io package. Java defines two types of streams. They are,1.Byte Stream : It provides a convenient means for handling input and output of byte.2.Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.

Page 150: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Byte Stream ClassesByte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream.

These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.

Page 151: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Some important Byte stream classes.

These classes define several key methods. Two most important are 1.read() : reads byte of data.2.write() : Writes byte of data.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStreamAn output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

Page 152: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Character Stream ClassesCharacter stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer.

These two abstract classes have several concrete classes that handle unicode character.

Page 153: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Some important Charcter stream classes.

Stream class DescriptionBufferedReader Handles buffered input stream.BufferedWriter Handles buffered output stream.FileReader Input stream that reads from file.FileWriter Output stream that writes to file.InputStreamReader Input stream that translate byte to characterOutputStreamReader Output stream that translate character to byte.PrintWriter Output Stream that contain print() and println() method.Reader Abstract class that define character stream inputWriter Abstract class that define character stream output

Page 154: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Reading Console InputWe use the object of BufferedReader class to take inputs from the keyboard.

Page 155: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Reading Charactersread() method is used with BufferedReader object to read characters. As this function returns integer type value has we need to use typecasting to convert it into char type.

Int read() throws IOException

Below is a simple example explaining character input.

Class CharRead{public static void main( String args[]) {BufferedReader br = new BufferedReader(new InputstreamReader(System.in));char c = (char)br.read(); //Reading character }}

Page 156: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Reading Strings

To read string we have to use readLine() function with BufferedReader class's object.String readLine() throws IOException

Program to take String input from Keyboard in Javaimport java.io.*;classMyInput{public static void main(String[] args) { String text;InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);text = br.readLine(); //Reading String System.out.println(text); }}

Page 157: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Program to read from a file using BufferedReader classimport java. io *;Class ReadTest{public static void main(String[] args) {try { File fl = new File("d:/myfile.txt");BufferedReader br = new BufferedReader (new FileReader(fl)) ; String str;while ((str=br.readLine())!=null) {System.out.println(str); }br.close();fl.close(); }catch (IOException e){ e.printStackTrace(); } }}

Page 158: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Program to write to a File using FileWriter classimport java. io *;Class WriteTest{public static void main(String[] args) {try { File fl = new File("d:/myfile.txt"); String str="Write this string to my file";FileWriterfw = new FileWriter(fl) ;fw.write(str);fw.close();fl.close(); }catch (IOException e){ e.printStackTrace(); } }}

Page 159: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Object and Class in Java we will learn about java objects and classes. In object-oriented programming technique, we design a program using objects and classes.Object is the physical as well as logical entity whereas class is the logical entity only. Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tengible and intengible). The example of integible object is banking system.

Page 160: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

An object has three characteristics:

state: represents data (value) of an object. behavior: represents the behavior (functionality) of an object such as deposit, withdraw

etc. identity: Object identity is typically implemented via a unique ID. The value of the ID is

not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.

Page 161: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Class in Java

A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.

A class in java can contain:

data member method constructor block class and interface

Syntax to declare a class:

1. class <class_name>{ 2. data member; 3. method; 4. }

Page 162: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Simple Example of Object and Class

In this example, we have created a Student class that have two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value.

1. class Student1{ 2. int id;//data member (also instance variable) 3. String name;//data member(also instance variable) 4. 5. public static void main(String args[]){ 6. Student1 s1=new Student1();//creating an object of Student 7. System.out.println(s1.id); 8. System.out.println(s1.name); 9. } 10. }

Test it Now Output:0 null

Page 163: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Instance variable in Java

A variable that is created inside the class but outside the method, is known as instance variable.Instance variable doesn't get memory at compile time.It gets memory at runtime when object(instance) is created.That is why, it is known as instance variable.

Method in Java

In java, a method is like function i.e. used to expose behaviour of an object.

Advantage of Method

Code Reusability Code Optimization

new keyword

The new keyword is used to allocate memory at runtime.

Page 164: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Example of Object and class that maintains the records of students

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method on it. Here, we are displaying the state (data) of the objects by invoking the displayInformation method.

1. class Student2{ 2. int rollno; 3. String name; 4. 5. void insertRecord(int r, String n){ //method 6. rollno=r; 7. name=n; 8. } 9. 10. void displayInformation(){System.out.println(rollno+" "+name);}//method 11. 12. public static void main(String args[]){ 13. Student2 s1=new Student2(); 14. Student2 s2=new Student2(); 15. 16. s1.insertRecord(111,"Karan"); 17. s2.insertRecord(222,"Aryan"); 18. 19. s1.displayInformation(); 20. s2.displayInformation(); 21. 22. } 23. }

Output:111 Karan 222 Aryan

Page 165: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

As you see in the above figure, object gets the memory in Heap area and reference variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.

Page 166: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Another Example of Object and Class

There is given another example that maintains the records of Rectangle class. Its exaplanation is same as in the above Student class example.

1. class Rectangle{ 2. int length; 3. int width; 4. 5. void insert(int l,int w){ 6. length=l; 7. width=w; 8. } 9. 10. void calculateArea(){System.out.println(length*width);} 11. 12. public static void main(String args[]){ 13. Rectangle r1=new Rectangle(); 14. Rectangle r2=new Rectangle(); 15. 16. r1.insert(11,5); 17. r2.insert(3,15); 18. 19. r1.calculateArea(); 20. r2.calculateArea(); 21. } 22. }

Output:55 45

Page 167: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

By new keyword By newInstance() method By clone() method By factory method etc.

We will learn, these ways to create the object later.

Page 168: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Annonymous object

Annonymous simply means nameless.An object that have no reference is known as annonymous object.

If you have to use an object only once, annonymous object is a good approach.

1. class Calculation{ 2. 3. void fact(int n){ 4. int fact=1; 5. for(int i=1;i<=n;i++){ 6. fact=fact*i; 7. } 8. System.out.println("factorial is "+fact); 9. } 10. 11. public static void main(String args[]){ 12. new Calculation().fact(5);//calling method with annonymous object 13. } 14. }

Output:Factorial is 120

Page 169: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.

1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

Let's see the example:

1. class Rectangle{ 2. int length; 3. int width; 4. 5. void insert(int l,int w){ 6. length=l; 7. width=w; 8. } 9. 10. void calculateArea(){System.out.println(length*width);} 11. 12. public static void main(String args[]){ 13. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects 14. 15. r1.insert(11,5); 16. r2.insert(3,15); 17. 18. r1.calculateArea(); 19. r2.calculateArea(); 20. } 21. }

Output:55 45

Page 170: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

class Definition: A class is a collection of objects of similar type. Once a class is defined, any number of objects can be produced which belong to that class. Class Declaration class classname { … ClassBody … }

Page 171: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Objects are instances of the Class. Classes and Objects are very much related to each other. Without objects you can't use a class.

A general class declaration: class name1 { //public variable declaration void methodname() { //body of method… //Anything } }

Page 172: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Now following example shows the use of method. class Demo { private int x,y,z; public void input() { x=10; y=15; } public void sum() { z=x+y; } public void print_data() { System.out.println(―Answer is =‖ +z); }

Page 173: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

public static void main(String args[]) { Demo object=new Demo(); object.input(); object.sum(); object.print_data(); } }

In program, Demo object=new Demo(); object.input(); object.sum(); object.print_data(); In the first line we created an object. The three methods are called by using the dot operator. When we call a method the code inside its block is executed. The dot operator is used to call methods or access them.

Page 174: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Creating “main” in a separate class We can create the main method in a separate class, but during compilation we need to make sure that you compile the class with the main method. class Demo { private int x,y,z; public void input() { x=10; y=15; } public void sum() { z=x+y; } public void print_data() { System.out.println(“Answer is =“ +z); } }

Page 175: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

class SumDemo { public static void main(String args[]) { Demo object=new Demo(); object.input(); object.sum(); object.print_data(); } }

Page 176: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

use of dot operator We can access the variables by using dot operator. Following program shows the use of dot operator. class DotDemo { int x,y,z; public void sum(){ z=x+y; } public void show(){ System.out.println("The Answer is "+z); } }

Page 177: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

class Demo1 { public static void main(String args[]){ DotDemo object=new DotDemo(); DotDemo object2=new DotDemo(); object.x=10; object.y=15; object2.x=5; object2.y=10; object.sum(); object.show(); object2.sum(); object2.show(); }} output:

C:\cc>javac Demo1.java C:\cc>java Demo1 The Answer is 25 The Answer is 15

Page 178: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Instance Variable All variables are also known as instance variable. This is because of the fact that each instance or object has its own copy of values for the variables. Hence other use of the ―dot” operator is to initialize the value of variable for that instance. Methods with parameters

Page 179: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Following program shows the method with passing parameter. class prg { int n,n2,sum; public void take(int x,int y) { n=x; n2=y; } public void sum() { sum=n+n2; } public void print() { System.out.println("The Sum is"+sum); } } }

Page 180: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

class prg1 { public static void main(String args[]) { prg obj=new prg(); obj.take(10,15); obj.sum(); obj.print(); }

Page 181: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Methods with a Return Type When method return some value that is the type of that method. For Example: some methods are with parameter but that method did not return any value that means type of method is void. And if method return integer value then the type of method is an integer. Following program shows the method with their return type. class Demo1 { int n,n2; public void take( int x,int y) { n=x; n=y; } public int process() { return (n+n2); } }

Page 182: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

class prg { public static void main(String args[]) { int sum; Demo1 obj=new Demo1(); obj.take(15,25); sum=obj.process(); System.out.println("The sum is"+sum); } }

Output: The sum is25

Page 183: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Method Overloading Method overloading means method name will be same but each method should be different parameter list. class prg1 { int x=5,y=5,z=0; public void sum() { z=x+y; System.out.println("Sum is "+z); } public void sum(int a,int b) { x=a; y=b; z=x+y; System.out.println("Sum is "+z); }

Page 184: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

public int sum(int a) { x=a; z=x+y; return z; } } class Demo { public static void main(String args[]) { prg1 obj=new prg1(); obj.sum(); obj.sum(10,12); System.out.println(+obj.sum(15)); } }

Output: sum is 10 sum is 22 27

Page 185: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Method Overloading in JavaIf a class have multiple methods by same name but different parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behaviour of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Page 186: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

Advantage of method overloading?

Method overloading increases the readability of the program.Different ways to overload the method

•In java, Methood Overloading is not possible by changing the return type of the method.

Page 187: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.1.class Calculation{  2.  void sum(int a,int b){System.out.println(a+b);}  3.  void sum(int a,int b,int c){System.out.println(a+b+c);}  4.    public static void main(String args[]){  5.  Calculation obj=new Calculation();  6.  obj.sum(10,10,10);  7.  obj.sum(20,20);  8.    }  9.}  Output:30 40

Page 188: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Example of Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.1.class Calculation2{  2.  void sum(int a,int b){System.out.println(a+b);}  3.  void sum(double a,double b){System.out.println(a+b);}  4.    public static void main(String args[]){  5.  Calculation2 obj=new Calculation2();  6.  obj.sum(10.5,10.5);  7.  obj.sum(20,20);  8.    }  9.}  Output:21.0 40

Page 189: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Why Method Overloaing is not possible by changing the return type of method?In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur:because there was problem:1.class Calculation3{  2.  int sum(int a,int b){System.out.println(a+b);}  3.  double sum(int a,int b){System.out.println(a+b);}  4.  5.  public static void main(String args[]){  6.  Calculation3 obj=new Calculation3();  7.  int result=obj.sum(20,20); //Compile Time Error  8.  9.  }  10.}  int result=obj.sum(20,20); //Here how can java determine which sum() method should be called

Page 190: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Can we overload main() method?Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example: 1.class Overloading1{  2.  public static void main(int a){  3.  System.out.println(a);  4.  }  5.    6.  public static void main(String args[]){  7.  System.out.println("main() method invoked");  8.  main(10);  9.  }  10.}  Output:main() method invoked 10

Page 191: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Constructor in JavaConstructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.1.Constructor name must be same as its class name2.Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:1.Default constructor (no-arg constructor)2.Parameterized constructor

Page 192: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner
Page 193: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

A constructor that have no parameter is known as default constructor.

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.

Java Default ConstructorSyntax of default constructor:1.<class_name>(){}  

Example of default constructor1.class Bike1{  2.Bike1(){System.out.println("Bike is created");}  3.public static void main(String args[]){  4.Bike1 b=new Bike1();  5.}  6.}  Output:Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Page 194: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner
Page 195: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

What is the purpose of default constructor?Default constructor provides the default values to the object like 0, null etc. depending on the type.Example of default constructor that displays the default values1.class Student3{  2.int id;  3.String name;  4.  5.void display(){System.out.println(id+" "+name);}  6.  7.public static void main(String args[]){  8.Student3 s1=new Student3();  9.Student3 s2=new Student3();  10.s1.display();  11.s2.display();  12.}  13.}  Output:0 null0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.

Page 196: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

A constructor that have parameters is known as parameterized constructor. Parameterized constructor

is used to provide different values to the distinct objects.

In this example, we have created the constructor of Student class that have two parameters. We can have any number of

parameters in the constructor.

Java parameterized constructorWhy use parameterized constructor?Example of parameterized constructor•class Student4{  •    int id;  •    String name;  •      •    Student4(int i,String n){  •    id = i;  •    name = n;  •    }  •    void display(){System.out.println(id+" "+name);}  •       public static void main(String args[]){  •    Student4 s1 = new Student4(111,"Karan");  •    Student4 s2 = new Student4(222,"Aryan");  •    s1.display();  •    s2.display();  •   }  •}  Output:111 Karan222 Aryan

Page 197: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Constructor Overloading in JavaConstructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Example of Constructor Overloading1.class Student5{  2.    int id;  3.    String name;  4.    int age;  5.    Student5(int i,String n){  6.    id = i;  7.    name = n;  8.    }  9.    Student5(int i,String n,int a){  10.    id = i;  11.    name = n;  12.    age=a;  13.    }  14.    void display(){System.out.println(id+" "+name+" "+age);15.}      

Page 198: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

1.public static void main(String args[]){  2.    Student5 s1 = new Student5(111,"Karan");  3.    Student5 s2 = new Student5(222,"Aryan",25);  4.    s1.display();  5.    s2.display();  6.   }  7.}  Output:111 Karan 0222 Aryan 25

Page 199: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Difference between constructor and method in javaThere are many differences between constructors and methods. They are given below.

Java Constructor Java Method

Constructor is used to initialize the state of an object.

Method is used to expose behaviour of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you don't have any constructor.

Method is not provided by compiler in any case.

Constructor name must be same as the class name.

Method name may or may not be same as class name.

Page 200: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java.

They are:

•By constructor•By assigning the values of one object into another•By clone() method of Object class

Page 201: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

class Student6{      int id;      String name;      Student6(int i,String n) {      id = i;      name = n;      }            Student6(Student6 s){      id = s.id;      name =s.name;      }      void display(){System.out.println(id+" "+name);} 

we are going to copy the values of one object into another using java constructor.

Page 202: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

public static void main(String args[]){      Student6 s1 = new Student6(111,"Karan");      Student6 s2 = new Student6(s1);      s1.display();      s2.display();     }  }  Output:111 Karan111 Karan

Page 203: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Copying values without constructorWe can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

1. class Student72. {  3.     int id;  4.     String name;  5.     Student7(int i,String n)6. {  7.     id = i;  8.     name = n;  9.     }  10.     Student7(){}  11.     void display()12. {13. System.out.println(id+" "+name);14. }  

Page 204: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

15.public static void main(String args[]){  16.    Student7 s1 = new Student7(111,"Karan");  17.    Student7 s2 = new Student7();  18.    s2.id=s1.id;  19.    s2.name=s1.name;  20.    s1.display();  21.    s2.display();  22.   }  23.}  Output:111 Karan111 Karan

Page 205: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Does constructor return any value?

yes, that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method.

Page 206: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Java static keywordThe static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.The static can be:1.variable (also known as class variable)2.method (also known as class method)3.block4.nested class

Page 207: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Java static variableIf you declare any variable as static, it is known static variable.

•The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.

•The static variable gets memory only once in class area at the time of class loading.

Advantage of static variableIt makes your program memory efficient (i.e it saves memory).Understanding problem without static variable•class Student{  •     int rollno;  •     String name;  •     String college="ITS";  •}  

Page 208: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created. All student have its unique rollno and name so instance data member is good. Here, college refers to the common property of all objects. If we make it static,this field will get memory only once.

Java static property is shared to all objects.

Page 209: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Example of static variable1.//Program of static variable  2.  3.class Student8{  4.   int rollno;  5.   String name;  6.   static String college ="ITS";  7.     8.   Student8(int r,String n){  9.   rollno = r;  10.   name = n;  11.   }  12. void display (){System.out.println(rollno+" "+name+" "+college);}  13.  14. public static void main(String args[]){  15. Student8 s1 = new Student8(111,"Karan");  16. Student8 s2 = new Student8(222,"Aryan");  17.   18. s1.display();  19. s2.display();  20. }  21.}  Output:111 Karan ITS 222 Aryan ITS

Page 210: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner
Page 211: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Program of counter without static variableIn this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.•class Counter{  •int count=0;//will get memory when instance is created  •  •Counter(){  •count++;  •System.out.println(count);  •}  •  •public static void main(String args[]){  •  •Counter c1=new Counter();  •Counter c2=new Counter();  •Counter c3=new Counter();  •  • }  •}  Output:1 1 1

Page 212: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.

Program of counter by static variable•class Counter2{  •static int count=0;//will get memory only once and retain its value  •  •Counter2(){  •count++;  •System.out.println(count);  •}  •  •public static void main(String args[]){  •  •Counter2 c1=new Counter2();  •Counter2 c2=new Counter2();  •Counter2 c3=new Counter2();  •  • }  •}  Output:1 2 3

Page 213: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Java static methodIf you apply static keyword with any method, it is known as static method.•A static method belongs to the class rather than object of a class.•A static method can be invoked without the need for creating an instance of a class.•static method can access static data member and can change the value of it.Example of static method•//Program of changing the common property of all objects(static field).  •  •class Student9{  •     int rollno;  •     String name;  •     static String college = "ITS";  •       •     static void change(){  •     college = "BBDIT";  •     }  •  •     Student9(int r, String n){  •     rollno = r;  •     name = n;  •     }  

Page 214: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

16.      void display (){System.out.println(rollno+" "+name+" "+college);}  

17.   18.     public static void main(String args[]){  19.     Student9.change();  20.   21.     Student9 s1 = new Student9 (111,"Karan");  22.     Student9 s2 = new Student9 (222,"Aryan");  23.     Student9 s3 = new Student9 (333,"Sonoo");  24.   25.     s1.display();  26.     s2.display();  27.     s3.display();  28.     }  29. }  Output:111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT

Page 215: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Another example of static method that performs normal calculation

1.//Program to get cube of a given number by static method  2.  3.class Calculate4.{  5.  static int cube(int x)6.{  7.  return x*x*x;  8.  }  9.  10.  public static void main(String args[])11.{  12.  int result=Calculate.cube(5);  13.  System.out.println(result);  14.  }  15.}  Output:125

Page 216: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method directly.

2. this and super cannot be used in static context.

Restrictions for static method1.class A{  2. int a=40;//non static  3.   4. public static void main(String args[]){  5.  System.out.println(a);  6. }  7.}        

Output:Compile Time Error

Page 217: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.

why java main method is static?

Java static block•Is used to initialize the static data member.•It is executed before main method at the time of classloading.Example of static block•class A2{  •  static{System.out.println("static block is invoked");}  •  public static void main(String args[]){  •   System.out.println("Hello main");  •  }  •}  Output:static block is invoked Hello main

Page 218: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Can we execute a program without main() method?Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.1.class A32.{  3.  static4.{  5.  System.out.println("static block is invoked");  6.  System.exit(0);  7.  }  8.}  Output:static block is invoked (if not JDK7)

In JDK7 and above, output will be:Output:Error: Main method not found in class A3, please define the main method as:public static void main(String[] args)

Page 219: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

this keyword in javaThere can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.

Usage of java this keywordHere is given the 6 usage of java this keyword.•this keyword can be used to refer current class instance variable.•this() can be used to invoke current class constructor.•this keyword can be used to invoke current class method (implicitly)•this can be passed as an argument in the method call.•this can be passed as argument in the constructor call.•this keyword can also be used to return the current class instance.

Suggestion: If you are beginner to java, lookup only two usage of this keyword.

Page 220: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner
Page 221: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.

The this keyword can be used to refer current class instance variable.

Let's understand the problem if we don't use this keyword by the example given below:

Understanding the problem without this keyword1.class Student10{  2.    int id;  3.    String name;  4.      5.    student(int id,String name){  6.    id = id;  7.    name = name;  8.    }  9.    void display(){System.out.println(id+" "+name);}  10.  11.    public static void main(String args[]){  12.    Student10 s1 = new Student10(111,"Karan");  13.    Student10 s2 = new Student10(321,"Aryan");  14.    s1.display();  15.    s2.display();  16.    }  17.}  Output:0 null 0 null

Page 222: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable.

Solution of the above problem by this keyword1.//example of this keyword  2.class Student11{  3.    int id;  4.    String name;  5.      6.    Student11(int id,String name){  7.    this.id = id;  8.    this.name = name;  9.    }  10.    void display(){System.out.println(id+" "+name);}  11.    public static void main(String args[]){  12.    Student11 s1 = new Student11(111,"Karan");  13.    Student11 s2 = new Student11(222,"Aryan");  14.    s1.display();  15.    s2.display();  16.}  17.}  Output111 Karan 222 Aryan

Page 223: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner
Page 224: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:

Program where this keyword is not required•class Student12{  •    int id;  •    String name;  •      •    Student12(int i,String n){  •    id = i;  •    name = n;  •    }  •    void display(){System.out.println(id+" "+name);}  •    public static void main(String args[]){  •    Student12 e1 = new Student12(111,"karan");  •    Student12 e2 = new Student12(222,"Aryan");  •    e1.display();  •    e2.display();  •}  •}  Output:111 Karan 222 Aryan

Page 225: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

this() can be used to invoked current class constructor. The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor.1.//Program of this() constructor call (constructor chaining)  2.  3.class Student13{  4.    int id;  5.    String name;  6.    Student13(){System.out.println("default constructor is invoked");}  7.      8.    Student13(int id,String name){  9.    this ();//it is used to invoked current class constructor.  10.    this.id = id;  11.    this.name = name;  12.    }  13.    void display(){System.out.println(id+" "+name);}  14.      15.    public static void main(String args[]){  16.    Student13 e1 = new Student13(111,"karan");  17.    Student13 e2 = new Student13(222,"Aryan");  18.    e1.display();  19.    e2.display();  20.   }  21.}  Output: default constructor is invoked default constructor is invoked 111 Karan 222 Aryan

Page 226: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword.

Where to use this() constructor call?1.class Student14{  2.    int id;  3.    String name;  4.    String city;  5.      6.    Student14(int id,String name){  7.    this.id = id;  8.    this.name = name;  9.    }  10.    Student14(int id,String name,String city){  11.    this(id,name);//now no need to initialize id and name  12.    this.city=city;  13.    }  14.    void display(){System.out.println(id+" "+name+" "+city);}  15.          public static void main(String args[]){  16.    Student14 e1 = new Student14(111,"karan");  17.    Student14 e2 = new Student14(222,"Aryan","delhi");  18.    e1.display();  19.    e2.display();  20.   }  21.}  Output:111 Karan null 222 Aryan delhi

Page 227: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner

Call to this() must be the first statement in constructor.1.class Student15{  2.    int id;  3.    String name;  4.    Student15(){System.out.println("default constructor is invoked");}  5.      6.    Student15(int id,String name){  7.    id = id;  8.    name = name;  9.    this ();//must be the first statement  10.    }  11.    void display(){System.out.println(id+" "+name);}  12.      13.    public static void main(String args[])14.{  15.    Student15 e1 = new Student15(111,"karan");  16.    Student15 e2 = new Student15(222,"Aryan");  17.    e1.display();  18.    e2.display();  19.   }  20.}  Output:Compile Time Error

Page 228: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner
Page 229: Data types: A data type is a scheme for representing values. An example is int which is the Integer, a data type Values are not just numbers, but any manner