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

Lect-4 Introduction To JAVA - 2

1. The document discusses various Java programming concepts including multidimensional arrays, operators, expressions, control statements, and type conversion. 2. It provides examples and explanations of different types of operators, expressions, control statements like if/else, for loops, and jump statements. 3. The document also covers type conversion between primitive data types including widening, narrowing, implicit and explicit conversion.

Uploaded by

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

Lect-4 Introduction To JAVA - 2

1. The document discusses various Java programming concepts including multidimensional arrays, operators, expressions, control statements, and type conversion. 2. It provides examples and explanations of different types of operators, expressions, control statements like if/else, for loops, and jump statements. 3. The document also covers type conversion between primitive data types including widening, narrowing, implicit and explicit conversion.

Uploaded by

Darshan Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

CS-201/CS-261

Object Oriented Design &


Programming/Lab
Multidimensional Arrays
• Multidimensional arrays are arrays of
arrays:
1) declaration: int array[][];
2) creation: int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
Keywords
Operators Types
• Java operators are used to build value
expressions.
• Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise
Arithmetic assignments

+= v += expr; v = v + expr ;

-= v -=expr; v = v - expr ;

*= v *= expr; v = v * expr ;

/= v /= expr; v = v / expr ;

%= v %= expr; v = v % expr ;
Basic Arithmetic Operators

+ op1 + op2 ADD

- op1 - op2 SUBSTRACT

* op1 * op2 MULTIPLY

/ op1 / op2 DIVISION

% op1 % op2 REMAINDER


Relational operator
== Equals to Apply to any type

!= Not equals to Apply to any type

> Greater than Apply to numerical type

< Less than Apply to numerical type

>= Greater than or equal Apply to numerical type

<= Less than or equal Apply to numerical type


Logical operators

& op1 & op2 Logical AND

| op1 | op2 Logical OR

&& op1 && op2 Short-circuit


AND
|| op1 || op2 Short-circuit
OR
! ! op Logical NOT

^ op1 ^ op2 Logical XOR


Bit wise operators
~ ~op Inverts all bits

& op1 & op2 Produces 1 bit if both operands are 1

| op1 |op2 Produces 1 bit if either operand is 1

^ op1 ^ op2 Produces 1 bit if exactly one operand is


1
>> op1 >> op2 Shifts all bits in op1 right by the value
of op2
<< op1 << op2 Shifts all bits in op1 left by the value
of op2
Bit wise operators
int a = 32;
a = a >> 2;
What is the value of a now?

int a = 35;
a = a >> 2;
What is the value of a now?

int a, b = 3;
a >> b + 3;
What is the value of a now?
Short Circuit logical operators
• Boolean AND and OR operators
• Example:
if (denom != 0 && num / denom > 10 )
Expressions
• An expression is a construct made up of variables,
operators, and method invocations, which are
constructed according to the syntax of the
language, that evaluates to a single value.
• Examples of expressions are in bold below:

int number = 0;
anArray[0] = 100;
System.out.println ("Element 1 at index 0: " +
anArray[0]);
int result = 1 + 2; // result is now 3
if(value1 == value2)
System.out.println("value1 == value2");
Expressions
 The data type of the value returned by an expression
depends on the elements used in the expression.
 The expression number = 0 returns an int because the
assignment operator returns a value of the same data type
as its left-hand operand; in this case, number is an int.

 The Java programming language allows you to construct


compound expressions from various smaller expressions as
long as the data type required by one part of the expression
matches the data type of the other.

 Here's an example of a compound expression: 1*2*3


Control Statements
• Java control statements cause the flow of
execution to advance and branch based on the
changes to the state of the program.
• Control statements are divided into three groups:

1. selection statements allow the program to choose


different parts of the execution based on the outcome
of an expression
2. iteration statements enable program execution to repeat
one or more statements
3. jump statements enable your program to execute in a
non-linear fashion
Selection Statements
• Java selection statements allow to control the
flow of program’s execution based upon
conditions known only during run-time.
• Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch
Selection Statements
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;

if(month == 12 || month == 1 || month == 2)


season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";

System.out.println("April is in the " + season + ".");


}
}
Selection Statements
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
Selection Statements
// 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:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more.");
}
}
}
Iteration Statements
• Java iteration statements enable
repeated execution of part of a program
until a certain termination condition
becomes true.
• Java provides three iteration statements:
1) while
2) do-while
3) for
Jump Statements
• Java jump statements enable transfer of
control to other parts of program.
• Java provides three jump statements:
1) break break label
2) continue
3) return
• In addition, Java supports exception
handling that can also alter the control
flow of a program.
Jump Statements
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;

first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
} Before the break
} This is after the break
Jump Statements
class BreakLoop4 {
public static void main(String args[]) {
outer: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break outer;
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}

Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete


Jump Statements
class Break5 {
public static void main(String args[]) {

one: for(int i=0; i<3; i++) {


System.out.print("Pass " + i + ": ");
}

for(int j=0; j<100; j++) {


if(j == 10) break one;
System.out.print(j + " ");
}
}
}
Jump Statements
class NoBody {
public static void main(String args[]) {
int i, j;

i = 100;
j = 200;

while(++i < --j) ; // no body in this loop

System.out.println(“The value of i is " + i);


}
}
Type Conversion
• Size Direction of Data Type
– Widening Type Conversion (Casting down)
• Smaller Data Type → Larger Data Type
– Narrowing Type Conversion (Casting up)
• Larger Data Type → Smaller Data Type
• Conversion done in two ways
– Implicit type conversion
• Carried out by compiler automatically
– Explicit type conversion
• Carried out by programmer using casting
Type Conversion

• Widening Type Conversion


– Implicit conversion by compiler
automatically

byte -> short, int, long, float, double


short -> int, long, float, double
char -> int, long, float, double
int -> long, float, double
long -> float, double
float -> double
Type Conversion
• Narrowing Type Conversion
– Programmer should describe the
conversion explicitly

byte -> char


short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char, int
float -> byte, short, char, int, long
double -> byte, short, char, int, long, float
Type Conversion
• byte and short are always promoted to int
• if one operand is long, the whole expression
is promoted to long
• if one operand is float, the entire
expression is promoted to float
• if any operand is double, the result is
double
Type Casting

• General form: (targetType) value


• Examples:
1) integer value will be reduced module
bytes range:
int i;
byte b = (byte) i;

2) floating-point value will be truncated to


integer value:
float f;
int i = (int) f;
Simple Java Program
• A class to display a simple message:
class MyProgram
{
public static void main(String[] args)
{
System.out.println(“First Java
program.");
}
}
What is an Object?
• Real world objects are things that have:
1) state
2) behavior
Example: your dog:
• state – name, color, breed, sits?, barks?, wages
tail?, runs?
• behavior – sitting, barking, waging tail, running
• A software object is a bundle of variables (state)
and methods (operations).
What is a Class?
• A class is a blueprint that defines the
variables and methods common to all
objects of a certain kind.
• Example: ‘your dog’ is a object of the class
Dog.
• An object holds values for the variables
defines in the class.
• An object is called an instance of the Class
Class
• A basis for the Java language.
• Each concept we wish to describe in Java
must be included inside a class.
• A class defines a new data type, whose
values are objects:
• A class is a template for objects
• An object is an instance of a class
Object Creation
• A variable is declared to refer to the objects of
type/class String:
String s;
• The value of s is null; it does not yet refer to any
object.
• A new String object is created in memory with
initial “abc” value:
• String s = new String(“abc”);
• Now s contains the address of this new object.
Object Destruction
• A program accumulates memory through its
execution.
• Two mechanism to free memory that is no
longer need by the program:
1) manual – done in C/C++
2) automatic – done in Java
• In Java, when an object is no longer
accessible through any variable, it is
eventually removed from the memory by
the garbage collector.
• Garbage collector is parts of the Java Run-
Time Environment.
Class Definition
 General form of a class:
class classname {
type instance-variable-1;

type instance-variable-n;

type method-name-1(parameter-list) {
… }
type method-name-2(parameter-list) {
… }

type method-name-m(parameter-list) {
… }
}
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }
Methods
 General form of a method definition:
type name(parameter-list) {
… return value;

}
 Components:
1) type - type of values returned by the method. If a
method does not return any value, its return type must be
void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
4) return value indicates what value is returned by the
method.
Example: Method
• Classes declare methods to hide their internal data
structures, as well as for their own internal use:
Within a class, we can refer directly to its member
variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height *
depth);
}
}
Parameterized Method
• Parameters increase generality and applicability
of a method:
1) method without parameters
int square() { return 10*10; }
2) method with parameters
int square(int i) { return i*i; }
• Parameter: a variable receiving value at the time
the method is invoked.
• Argument: a value passed to the method when it
is invoked.
Constructor
• A constructor initializes the instance variables of
an object.
• It is called immediately after the object is created
but before the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default
return type of a class
• constructor is the same class
• When the class has no constructor, the default
constructor automatically initializes all its instance
variables with zero.
Example: Constructor
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}
Parameterized Constructor
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of
variables and methods.
• Encapsulation, safely sealing data within the
capsule of the class Prevents programmers from
relying on details of class implementation, so you
can update without worry
• Helps in protecting against accidental or wrong
usage.
• Keeps code elegant and clean (easier to maintain)
Access Modifiers: Public, Private,
Protected
• Public: keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.

• Default(No visibility modifier is specified): it


behaves like public in its package and private in
other packages.

• Default Public keyword applied to a class, makes


it available/visible everywhere. Applied to a
method or variable, completely visible.
Access Modifiers: Public, Private,
Protected
• Private fields or methods for a class only
visible within that class. Private members
are not visible within subclasses, and are
not inherited.

• Protected members of a class are visible


within the class, subclasses and also within
all classes that are in the same package as
that class.
Visibility
public class Circle {
private double x,y,r;

// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
Keyword this

• Can be used by any object to refer to


itself in any class method
• Typically used to
– Avoid variable name collisions
– Pass the receiver as an argument
– Chain constructors
Keyword this
• Keyword this allows a method to refer to the
object that invoked it.
• It can be used inside any method to refer to the
current object:
Box(double width, double height, double
depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Garbage Collection
• Garbage collection is a mechanism to remove objects from
memory when they are no longer needed.

• Garbage collection is carried out by the garbage collector:


1) The garbage collector keeps track of how many
references an object has.
2) It removes an object from memory when it has no
longer any references.
3) Thereafter, the memory occupied by the object
can be allocated again.
4) The garbage collector invokes the finalize method.
finalize() Method
• A constructor helps to initialize an object just
after it has been created.
• In contrast, the finalize method is invoked just
before the object is destroyed:
1) implemented inside a class as:
protected void finalize() { … }
2) implemented when the usual way of
removing objects from memory is insufficient,
and some special actions has to be carried out
Stack Class
// This class defines an integer stack that can hold 10 values.
class Stack {
int stck[] = new int[10];
int tos;

// Initialize top-of-stack
Stack() {
tos = -1;
}

// Push an item onto the stack


void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}

// Pop an item from the stack


int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
Stack Class
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();

// push some numbers onto the stack


for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);

// pop those numbers off the stack


System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());

System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}

You might also like