Module 1
Module 1
Programming with
JAVA
– 23CSPC210
Object-Oriented Programming
• Two Paradigms
– All computer programs consist of two elements: code
and data.
• Furthermore, a program can be conceptually
organized around its code or around its data. That
is, some programs are written around “what is
happening” and others are written around “who
is being affected.”
• These are the two paradigms that govern how a
program is constructed.
Object-Oriented Programming
• process-oriented model
– The process-oriented model can be thought of as code
acting on data.
– C employ this model.
• object-oriented programming
– Object-oriented programming organizes a program
around its data (that is, objects) and a set of well-
defined interfaces to that data.
– An object-oriented program can be characterized as
data controlling access to code.
Object-Oriented Programming
Object-Oriented Programming
class
{
//member data
int x;
int y;
//member method
public void getxy()
{
//code
}
public void putxy()
{
//code
}
}
A First Simple Program
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
type var-name;
type specifies the type of variable being declared,
and var-name is the name of the variable.
Using Blocks of Code
• Java allows two or more statements to be grouped
into blocks of code, also called code blocks.
• This is done by enclosing the statements between
opening and closing curly braces.
• Once a block of code has been created, it becomes
a logical unit that can be used any place that a
single statement can.
if(x < y) { // begin a block
x = y;
y = 0;
} // end of block
/* Demonstrate a block of code. */
class BlockTest {
public static void main(String args[]) {
int x, y;
y = 20;
// the target of this loop is a block
for(x = 0; x<10; x++) {
[Link]("This is x: " + x);
[Link]("This is y: " + y);
y = y - 2;
}
}
} This is x: 3
Output: This is y: 14
This is x: 4 This is x: 7
This is x: 0
This is y: 12 This is y: 6
This is y: 20
This is x: 5 This is x: 8
This is x: 1
This is y: 10 This is y: 4
This is y: 18
This is x: 6 This is x: 9
This is x: 2
This is y: 8 This is y: 2
This is y: 16
Lexical Issues
• Java programs are a collection of whitespace,
identifiers, literals, comments, operators, separators,
and keywords.
• Whitespace
– Java is a free-form language. This means that you do not
need to follow any special indentation rules.
– In Java, whitespace is a space, tab, or newline.
• Identifiers
– Identifiers are used for class names, method names, and
variable names.
– An identifier may be any descriptive sequence of uppercase
and lowercase letters, numbers, or the underscore and
dollar-sign characters.
– They must not begin with a number.
– Java is case-sensitive.
Lexical Issues
• Literals
– A constant value in Java is created by using a literal
representation of it.
• Comments
– Three types of comments defined by Java.
Lexical Issues
• Separators
– In Java, there are a few characters that are used as
separators.
– The most commonly used separator in Java is the
semicolon.
Lexical Issues
• The Java Keywords
– There are 50 keywords currently defined in the Java
language
– These keywords cannot be used as names for a variable,
class, or method.
– In addition to the keywords, Java reserves the following:
true, false, and null. These are values defined by Java.
The Java Class Libraries
• println( ) and print( ), these methods are
members of the System class.
Java Is a Strongly Typed Language
• Java is a strongly typed language.
• First, every variable has a type, every expression has
a type, and every type is strictly defined.
• Second, all assignments, whether explicit or via
parameter passing in method calls, are checked for
type compatibility.
• There are no automatic coercions or conversions of
conflicting types as in some languages.
• The Java compiler checks all expressions and
parameters to ensure that the types are compatible.
• Any type mismatches are errors that must be
corrected before the compiler will finish compiling
the class.
Data Types in Java
• Data types specify the different sizes and values that can be
stored in the variable.
• There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
• Integers: This group includes byte, short, int, and long,
which are for whole-valued signed numbers.
• Floating-point numbers: This group includes float and
double, which represent numbers with fractional precision.
• Characters :This group includes char, which represents
symbols in a character set, like letters and numbers.
• Boolean: This group includes boolean, which is a special
type for representing true/false values.
Data Default Default Example Range
Type Value size
boolean false 1 bit Boolean true and false
one = false
char '\u0000' 2 byte char ch = '\u0000' (or 0) to '\uffff' (or 65,535)
'A' (or) 0 to 65,536
byte 0 1 byte byte a = 10 -128 to 127
Short 0 2 byte short s = –32,768 to 32,767
10000
int 0 4 byte int a = –2,147,483,648 to 2,147,483,647
100000
long 0L 8 byte long a = –9,223,372,036,854,775,808 to
100000L 9,223,372,036,854,775,807
float 0.0f 4 byte float f1 = 1.4e–045 to 3.4e+038
234.5f
double 0.0d 8 byte double d1 4.9e–324 to 1.8e+308
= 12.3
char uses 2 byte in java and \u0000, java uses Unicode system not ASCII code system.
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
[Link]("Area of circle is " + a);
}
}
Output:
ch1 contains X
ch1 is now Y
Exercises
• Addition of two numbers.
• Convert Fahrenheit to Celsius.
• Area of circle
• Simple Interest.
int x = 10;
int y = 9;
[Link](x > y); // returns true, because 10 is higher than 9
Integer Literals
• Any whole number value is an integer literal. Examples are
1, 2, 3, and 42. These are all decimal values, meaning they
are describing a base 10 number.
• There are two other bases which can be used in integer
literals, octal (base eight) and hexadecimal (base 16).
• Octal values are denoted in Java by a leading zero. Ex: 05
• Normal decimal numbers cannot have a leading zero.
• Hexadecimal constant with a leading zero-x, (0x or 0X). Ex:
0x5
• The range of a hexadecimal digit is 0 to 15, so A through F
(or a through f ).
• For binary, leading 0b or 0B
• Ex: 0b1000001; (‘A’)
public class Test
{
public static void main(String args[])
{
char c = 0b1000001; // Binary
[Link](c);
c=0101; //Octal
[Link](c);
c=0x41; //Hexadecimal
[Link](c);
}
}
Floating-Point Literals
• Floating-point numbers represent decimal values with
a fractional component.
• They can be expressed in either standard or scientific
notation.
• Standard notation consists of a whole number
component followed by a decimal point followed by a
fractional component (ex, 2.0, 3.14159, and 0.6667).
• Scientific notation uses a standard-notation, floating-
point number plus a suffix that specifies a power of 10
by which the number is to be multiplied.
• The exponent is indicated by an E or e followed by a
decimal number, which can be positive or negative.
• Examples include 6.022E23, 314159E–05,and 2e+100.
Floating-Point Literals
• Floating-point literals in Java default to double
precision.
• To specify a float literal, you must append an F or f
to the constant.
• Ex: 3.4f
• explicitly specify a double literal by appending a D
or d.
• Ex: 2.5d
Boolean Literals
• Boolean literals are simple.
• There are only two logical values that a boolean
value can have, true and false.
• The values of true and false do not convert into
any numerical representation.
• The true literal in Java does not equal 1, nor does
the false literal equal 0.
Character Literals
• Characters in Java are indices into the Unicode
character set.
• They are 16-bit values that can be converted into
integers and manipulated with the integer
operators, such as the addition and subtraction
operators.
• A literal character is represented inside a pair of
single quotes.
• Ex: ‘a’, ‘z’, and ‘@’.
• For characters that are impossible to enter
directly, escape sequences, ‘\’’ for the single-quote
character and ‘\n’ for the newline character.
Character Literals
• There is also a mechanism for directly entering the
value of a character in octal or hexadecimal.
• For octal notation, use the backslash followed by
the three-digit number.
• For example, ‘\141’ is the letter ‘a’.
• For hexadecimal, enter a backslash-u (\u), then
exactly four hexadecimal digits.
• For example, ‘\u0061’ is the ISO-Latin-1 ‘a’
because the top byte is zero. ‘\ua432’ is a
Japanese Katakana character.
TABLE 3-1 Character Escape Sequences
public class EscapeExample
{
public static void main(String args[])
{
String str = new String ("My name is \'abcd\'");
[Link](str);
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++) //length is the of array
[Link](a[i]);
}
}
• Arrays can be initialized when they are declared.
• The process is much the same as that used to
initialize the simple types.
• An array initializer is a list of comma-separated
expressions surrounded by curly braces. The
commas separate the values of the array
elements.
• The array will automatically be created large
enough to hold the number of elements you
specify in the array initializer.
• There is no need to use new.
int a[]={1,2,3,4,5};
For-each Loop for Java Array
• We can also print the Java array using for-each
loop.
• The Java for-each loop prints the array elements
one by one.
• It holds an array element in a variable, then
executes the body of the loop.
for(data_type variable : array){
//body of the loop
}
public class PrintArray {
public static void main(String [] args){
String[] array = { "hi", "hello", "java"};
for(int i=0;i<12;i++)
{
[Link](month_names[i] + " is having " + month_days[i] + " days.");
}
}
}
• Print array elements
• Print array elements in reverse order
• Print odd elements
• Merge two arrays into third array
• Copy even elements to even array and odd
elements to odd array from the original array.
• Sort array elements
Multidimensional Arrays
• In Java, multidimensional arrays are actually arrays of
arrays.
• To declare a multidimensional array variable, specify
each additional index using another set of square
brackets.
int twoD[][] = new int[4][5];
• This allocates a 4 by 5 array and assigns it to twoD.
Syntax:
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
Jagged Array in Java
• Creating odd number of columns in a 2D array, it
is known as a jagged array.
• In other words, it is an array of arrays with
different number of columns.
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) { This program generates the following output:
int twoD[][] = new int[4][]; 0
twoD[0] = new int[1]; 12
345
twoD[1] = new int[2];
6789
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
• It is possible to initialize multidimensional arrays.
To do so, simply enclose each dimension’s
initializer within its own set of curly braces.
int arr[][]={
{1,2,3},
{2,4,5},
{4,4,5}
};
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}} Output:
123
245
445
// Demonstrate a three-dimensional array.
class ThreeDMatrix {
public static void main(String args[]) { output:
int threeD[][][] = new int[3][4][5]; 00000
int i, j, k; 00000
for(i=0; i<3; i++) 00000
for(j=0; j<4; j++)
00000
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
00000
for(i=0; i<3; i++) { 01234
for(j=0; j<4; j++) { 02468
for(k=0; k<5; k++)
0 3 6 9 12
[Link](threeD[i][j][k] + " ");
[Link]();
} 00000
[Link](); 02468
} •3 layers
•Each layer has 4 rows 0 4 8 12 16
}
•Each row has 5 columns 0 6 12 18 24
} So total elements = 3 × 4 × 5 = 60
elements
Alternative Array Declaration Syntax
• There is a second form used to declare an array:
type[ ] var-name;
int a1[] = new int[3];
int[] a2 = new int[3];
Therefore, ~5 results in -6
public class Bitoperators {
public static void main(String[] args) {
int a = 5;
int b = 7;
[Link]("a&b = " + (a & b));
[Link]("a|b = " + (a | b));
[Link]("a^b = " + (a ^ b));
// bitwise not ~0101=1010
// will give 2's complement of 1010 = -6
[Link]("~a = " + ~a); Output :
a &= b; a&b = 5
[Link]("a= " + a); a|b = 7
} a^b = 2
~a = -6
} a= 5
Relational Operators
• The OR operator results in true when A is true, no matter what B is. Similarly,
the AND operator results in false when A is false, no matter what B is.
• If you use the || and && forms, rather than the | and & forms of these operators,
Java will not bother to evaluate the right-hand operand when the outcome of the
expression can be determined by the left operand alone.
• This is very useful when the right-hand operand depends on the value of
the left one in order to function properly.
Short-Circuit Logical Operators
• Syntax
• if
• if-else
• if-else-if ladder
• nested if
• switch
• Java’s program control statements can be put into
the following categories:
– Selection
• Selection statements allow your program to choose
different paths of execution based upon the outcome of an
expression or the state of a variable.
– Iteration
• Iteration statements enable program execution to repeat
one or more statements (that is, iteration statements form
loops).
– jump
• Jump statements allow your program to execute in a
nonlinear fashion.
Control Statements
• The if Statement : The Java if
statement tests the condition.
• It executes the if block if
condition is true.
if(condition) {
// statement;
}
Syntax:
if(condition){
//code if condition is true
}
else{
//code if condition is false
}
//It is a program of odd and even number.
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
if(marks<35){
[Link]("fail");
}
else if(marks>=35 && marks<60){
[Link]("D grade");
}
else if(marks>=60 && marks<70){
[Link]("C grade");
}
else if(marks>=70 && marks<80){
[Link]("B grade");
}
else if(marks>=80 && marks<90){
[Link]("A grade");
}else if(marks>=90 && marks<100){
[Link]("A+ grade");
}else{
[Link]("Invalid!");
}
}
}
//Find out given no is +ve or –ve or zero
if(number>0){
[Link]("POSITIVE");
}else if(number<0){
[Link]("NEGATIVE");
}else{
[Link]("ZERO");
}
}
}
Nested if
• The nested if statement represents
the if block within another if block.
• Here, the inner if block condition
executes only when outer if block
condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
//Java Program to demonstrate the use of Nested If Statement.
default:
code to be executed if all cases are
not matched;
}
public class SwitchExample {
public static void main(String[] args) {
int number=2;
//Switch expression
switch(number){
//Case statements
case 1: [Link](“ONE");
break;
case 2: [Link](“TWO");
break;
case 3: [Link](“THREE");
break;
//Default case statement
default:[Link]("Not in 1, 2 or 3");
}
}
}
case 5: monthString="5 - May";
//Name of the month break;
case 6: monthString="6 - June";
public class SwitchMonthExample { break;
public static void main(String[] args) { case 7: monthString="7 - July";
//Specifying month number break;
int month=7; case 8: monthString="8 - August";
String monthString=""; break;
case 9: monthString="9 - September";
//Switch statement break;
switch(month){ case 10: monthString="10 - October";
//case statements within the switch block break;
case 11: monthString="11 - November";
case 1: monthString="1 - January"; break;
break; case 12: monthString="12 - December";
case 2: monthString="2 - February"; break;
break;
case 3: monthString="3 - March"; default:[Link]("Invalid Month!");
break;
case 4: monthString="4 - April"; }
break; //Printing month of the given number
[Link](monthString);
}
}
switch w/o break
• It executes all statements after the first match, if a
break statement is not present.
//without break statement
public class SwitchExample2 {
public static void main(String[] args) {
int num=2;
//switch expression with int value
switch(num){
//switch cases without break statements
Output:
case 1: [Link](“1");
2
case 2: [Link](“2"); 3
case 3: [Link](“3"); Not in 1, 2 or 3
default:[Link]("Not in 1, 2 or 3");
}
}
}
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1: OUTPUT:
case 2: i is less than 5
case 3: i is less than 5
case 4: i is less than 5
[Link]("i is less than 5"); i is less than 5
break; i is less than 5
case 5: i is less than 10
case 6: i is less than 10
case 7: i is less than 10
case 8: i is less than 10
case 9: i is less than 10
[Link]("i is less than 10"); i is 10 or more
break; i is 10 or more
default:
[Link]("i is 10 or more");
}
}
}
Nested Switch Statement
• We can use switch statement inside other switch
statement in Java.
• It is known as nested switch statement.
switch(expression1){
case value1:
//code to be executed;
break;
case value2:
switch(expression2){
case value21:
//code to be executed;
break; //optional
case value22:
break; //optional
default:
default code to be executed
}
break;
default:
code to be executed if all cases are not matched;
}
Example: -
You are searching for a department in a university and you’re asked to select a
school from a choice of three schools namely:
1. School of Arts
2. School of Business
3. School of Engineering
Having selected a school you are again provided with a list of departments that fall
under the department namely:
1. School of Arts
A. Department of finearts
B. Department of sketcharts
2. School of Business
A. Department of Commerce
B. Department of purchasing
3. School of Engineering
A. CSE
B. ECE
The initial choices for Computer Science, Business and Engineering schools would
be inside as a set of switch statements. Then various departments would then be
listed within inner switch statements beneath their respective schools.
import [Link].*;
import [Link];
class NestedExample
{
public static void main(String args[])
{
int a,b;
[Link]("[Link] of Arts\n");
[Link]("[Link] of Business\n");
[Link]("[Link] of Engineering\n");
[Link]("make your selection\n");
Scanner sobj = new Scanner([Link]);
a=[Link]();
switch (a)
{
case 1:
[Link]("You chose Arts\n" ); break;
case 2:
[Link]("You chose Business\n" ); break;
case 3:
[Link]("You chose Engineering\n" );
[Link]("[Link]\n" );
[Link]("[Link]\n" );
[Link]("make your selection\n"); b=[Link]();
switch(b)
{
case 1:
[Link]("You chose CSE\n" ); break;
case 2:
[Link]("You chose ECE" ); break;
defalut: [Link](“Invalid choice of department" );
}
break;
defalut: [Link](“Invalid choice of School" );
}
}
}
Iteration Statements
• Java’s iteration statements are for, while, and
do-while.
• These statements are called loops.
• A loop repeatedly executes the same set of
instructions until a termination condition is
met.
while
• The while loop is Java’s most fundamental loop
statement. It repeats a statement or block while its
controlling expression is true.
while(condition) {
// body of loop
}
• The condition can be any Boolean expression. The
body of the loop will be executed as long as the
conditional expression is true.
• When condition becomes false, control passes to the
next line of code immediately following the loop.
• The curly braces are unnecessary if only a single
statement is being repeated.
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
[Link](n);
n--;
} // The target of a loop can be empty.
} class NoBody {
} public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j) ; // no body in this loop
[Link]("Midpoint is " + i);
}
}
do-while
• The do-while loop always executes its body at
least once, because its conditional expression is at
the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
• Each iteration of the do-while loop first executes
the body of the loop and then evaluates the
conditional expression. If this expression is true,
the loop will repeat. Otherwise, the loop
terminates.
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
[Link](n);
n--;
} while(n > 0);
}
} do {
[Link]("Help on:");
[Link](" 1. if");
[Link](" 2. switch");
[Link](" 3. while");
[Link](" 4. do-while");
[Link]( ) is used to
[Link](" 5. for\n");
read characters from standard [Link]("Choose one:");
input. choice = (char) [Link]();
} while( choice < '1' || choice > '5');
for
• There are two forms of the for loop.
• The first is the traditional form of Java.
for(initialization; condition; iteration) {
// body
}
• The second is the new “for-each” form. The for-
each loop is essentially read-only.
for(type itr-var : collection) {
statement-block
}
for Loop Variations
for(int a=1, b=4; a<b; a++, b--)
{
}
for(int i=1; !done; i++) // Parts of the for loop can be empty.
class ForVar {
{ public static void main(String args[]) {
} int i;
boolean done = false;
i = 0;
for( ; !done; ) {
//infinite loop [Link]("i is " + i);
if(i == 10) done = true;
for( ; ; ) { i++;
// ... }
}
} }
// Use a for-each style for loop.
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
[Link]("Value is: " + x);
sum += x;
}
[Link]("Summation: " + sum);
}
}
// Use for-each style for on a two-dimensional array.
class ForEach3 {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
// give nums some values
for(int i = 0; i < 3; i++)
for(int j=0; j < 5; j++)
nums[i][j] = (i+1)*(j+1);
if(i == 3)
continue;
[Link](i);
}
}
}
// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
[Link]();
continue outer;
}
[Link](" " + (i * j));
}
}
[Link]();
}
}
return
• The return statement is used to explicitly
return from a method.
• That is, it causes program control to transfer
back to the caller of the method.
• The return statement immediately terminates
the method in which it is executed.
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
[Link]("Before the return.");
if(t)
return; // return to caller
[Link]("This won't execute.");
}
}
class Search {
public static void main(String args[]) {
if(found)
[Link]("Value found at position: " + pos);
else
[Link]("Value not found!");
}
}