SlideShare a Scribd company logo
Arrays
Control statements
Introduction to classes
Arrays
One-
dimensional
array
Declaring the
array
A list of items that can be given one variable
name using only one subscript and such a
variable is called one scripted variable or one
dimensional array.
Form1 : type arrayname[];
Form2: type [] arrayname;
Ex: int num[];
float avg[];
int[] counter;
float[] marks;
Note : we don’t enter size of the array in
declaration.
Creation of
array
After we declare the array we need to
create it in the memory
Java allows us to create arrays using
new operator only
Syntax : arrayname=new type[size];
Ex : number= new int[5];
avg=new float[10];
It is possible to combine declaration and
creation
int number=new int[5];
Initialization of
arrays
Syntax : arrayname[subscript]=value;
Ex :
number[0]=10;
number[1]=20;
Note :java creates the starting index with 0
and end with one less than the size of the
array.
type arrayname={list of values};
Ex: int num[]={10,20,30,40};
int a[]={1,2,3}; int b[]; b=a;
Assigning one
arrays to
another.
class demo12 {
public static void main(String[] args) {int[]
a=new int[5];
a[0]=211;a[1]=10;a[2]=12;
a[3]=21;a[4]=100;
int[] b=new int[5];
b=a;
System.out.println("array of b is:"+b);}}
 In java , all arrays store the
allocated size in a variable
named length.
 We can obtain the length of
array ‘a’ by a.length.
 Ex : int
arraylength=a.length
Array length
public class JavaArrayLengthExample
{
public static void main(String[] args)
{
String[] toppings = {"cheese", "pepperoni", "black olives"};
int arrayLength = toppings.length;
System.out.format("The Java array length is %d", arrayLength);
}
}
Output:
The Java array length is 3
Two-
dimensional
arrays
310 275 365
210 190 325
405 235 240
260 300 380
[0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
[2][0] [2][1] [2][2]
[3][0] [3][1] [3][2]
int myarray[][];
myarray=new int [5];
int myarray[][]=new int [5];
Creating Two-
dimensional
arrays
//Demonstrating two dimensional array
class Multable
{
final static int ROWS=10;
final static int COLUMNS=10;
public static void main(String args[])
{
int product[][]=new int[ROWS][COLUMNS];
int rows,columns;
System.out.println(“2’s multiplication table is ");
System.out.println(" ");
int i,j;
for(i=2;i<=ROWS;i++)
{
for(j=1;j<COLUMNS;j++)
{
product[i][j]=i*j;
System.out.println(“ "
+i+"*"+j+"="+ product[i][j]);
}
System.out.println("
");
}
}
}
Output:
2’s multiplication table is
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18
Beyond two dimensions, you can
create an array variable that represents
various lists, each list would contain
various internal lists, and each internal
list would contain its own components.
This is referred to as a
multidimensional array.
One of the rules you must follow is
that, as always, all members of the
array must be of the same type.
variable size
arrays or
Multi-
dimensional
array
Java treats multidimensional arrays as “array
of arrays”.
When you allocate memory for a
multidimensional array, you need only specify
the memory for the first (leftmost) dimension.
You can allocate the remaining dimensions
separately.
For example, this following code allocates
memory for the first dimension of twoD when it
is declared. It allocates the second dimension
manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
Creating
variable size
arrays
// Demonstrate a three-dimensional array of 3 by 4
by 5.
class ThreeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
Output:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 0 0 0 0
0 2 4 6 8
0 4 8 12 16
0 6 12 18 24
Control
statements
Any language uses control
statements to cause the flow of
execution to advance and
branch based on the state of
the program.
Why do we
need control
statements?
Control
Statements
Selection Iterative Jump
Control
Statements
categories
 Selection : to choose
different paths of execution
based on outcome or state
of the variable.
 Iterative : to repeat one or
more statements.
 Jump : to execute in non-
linear fashion.
Control
Statements
categories
If statement is conditional branch
statement.
If Syntax:
if(condition)statement1;
else statement2;
Ex : if(a>b)a=0;
else b=0;
Java’s
selection
statements
oIf
oswitch
Switch is multi-way branch
statement.
Syntax : switch(expression){
Case value1:
//statement sequence;
break;
Case value2:
//statement sequence;
break;
default:
//default statement sequence}
Switch
case
Java’s iterative
statements
o while
o do-while
o for
Iterative statements create what
we commonly call loops which
repeatedly executes the same set
of instructions until a termination
condition is met.
while syntax:
While(condition){
//body of loop
}
If the conditional expression controlling
a while loop is initially false , then the
body of the loop will not be executed at
all.
Sometimes it is desirable to execute the
body of loop at least once even if the
conditional expression is false.
Condition is checked at the end of the
loop.
syntax:
do{
//body of loop
}while(condition);
do- while
case
Syntax:
for(initialization ; condition ; iteration)
{ //body of loop
}
When loop starts the initialization
portion of the loop executes . Here
initialization expression is executed only
once.
Next condition is evaluated.
If the condition is true the body of the
loop is executed. If false then loop
terminates.
Then iteration is executed i . e
increments or decrements the loop
control variable
for loop
case
Used to transfer control to
another part of your program
Break statement has 3 uses:
1. Terminates a statement
sequence in switch
statement
2. To exit a loop
3. Civilized form of goto
Java’s jump
statements
o break
o continue
o return
// 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.");
}
}
}
break as
civilized form
of goto
continue
jump
statement
Skips the current iteration of a
for , while or do-while loop.
The unlabeled form skips to
the end of the innermost loop’s
body and evaluates Boolean
expression that controls the
loop.
break leaves the loop.
continue jumps to the next
iteration.
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.
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
The output from this program is shown here:
Before the return.
Return jump
statement
Introducing
classes
Class
fundamentals :
General form
of class
Class syntax:
Class classname{
type instancevariable1;
type instancevariable2;
Type methodname1(parameter
list){//body of method}
Type methodname2(parameter
list){//body of method}
Class name
convention
class name should be nouns ,
in mixed cases with the first
letter of each internal word
capitalized.
Ex : class CamelCase{
}
Variable
types
Instance
variables
Class/static
variables
Local
variables
what is
instance
variable?
 Instance variables are declared in
a class, but outside a method,
constructor or any block.
 When a space is allocated for an
object in the heap, a slot for each
instance variable value is created.
 Instance variables are created
when an object is created with the
use of the keyword 'new' and
destroyed when the object is
destroyed.
instance
variable
example
Public class vehicle
{
//instance variables of class
private int doors;
private int speed;
private string color;
}
what is
class/static
variable?
They begins their life when first
class loaded into memory and ends
when class is unloaded i . e they
remain in memory till class exist, so
these variables often called Class
variables.
 There only one copy of these
variables exist
These variables are having highest
scope that is they can be accessed
from any method/ block in a class
what is local
variable?
local variables are declared
anywhere inside method. their life
is started point they declared /
initialized and ends when method
completes.
Example of
types of
variables
public class Variables {
static int staticVariable = 1;
int instanceVariable = 2;
public void methodName(int
methodParameter) {
int methodLocalVariable = 3;
if (true) {
int blockVariable = 4;
}
}
}
simple
class
class box{
int width;
int height;
int depth;
}
Objects are conceptually similar to
real-world objects they too consist of
state and related behavior.
object stores its state in fields
(variables in some programming
languages) and exposes its behavior
through methods (functions in some
programming languages).
Methods operate on an object's internal
state and serve as the primary mechanism
for object-to-object communication.
What is an
object?
Declaring
objects
Box mybox=new Box();
This statement has 2 steps:
1. Box mybox;
//mybox is reference variable
1. mybox= new Box();
//allocate a box object
Declaring
objects
class Box {
int width;
int height;
int depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
int vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Assigning
object
reference
variable
Box b1=new box();
Box b2=b1;
//b1 = null;
Here, b1 has been set to null, but
b2 still points to the original object
Note : When you assign one object
reference variable to another object
reference variable, you are not creating
a copy of the object, you are only
making a copy of the reference.
b2
b1 Width
Height
Depth
Introducing
methods
Why use
methods?
Methods are how we
communicate with objects.
When we call or invoke a method
we are asking the objects to carry
out a task
 For reusable code
 To simplify
 For top-down programming
 To create conceptual units
 To parameterize code
More generally, method declarations have six
components, in order:
1.Modifiers—such as public, private, and others you
will learn about later.
2.The return type—the data type of the value
returned by the method, or void if the method does
not return a value.
3.The method name—the rules for field names
apply to method names as well, but the convention
is a little different.
4.The parameter list in parenthesis—a comma-
delimited list of input parameters, preceded by their
data types, enclosed by parentheses, (). If there are
no parameters, you must use empty parentheses.
5.An exception list—to be discussed later.
6.The method body, enclosed between braces—the
method's code, including the declaration of local
variables, goes here.
Method
components
Method name
convention
Method name should be
verbs , in mixed case with the
first letter lowercase , with the
first letter of each internal
word capitalized.
Ex : class CamelCase{
Void runFast()
}
General form of
methods
type-name(parameters list)
{
//body of the method
}
Ex: void volume()
{
System.out.println(“volume is”);
System.out.println(width*height*
depth);
]
Constructor and
its purpose
Constructor is a special type
of method that is used to
initialize the object.
It 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
constructors
1. Constructor name must be
same as it class name
2. Constructor must have no
explicit return type.
Types of
Constructors
1. Default constructor(no-arg
constructor)
2. Parameterized constructor.
A constructor that has no
parameters is known as default
constructor.
Class bike(){
Bike(){System.out.println(“bike
constructor”);}
Public static void main(){
bike b=new bike(); } }
Parameterized
constructors
A constructor that has parameters is
known as parameterized constructor.
Class student(){
Int id;
String name
student(int i, string n) { id=i; name=n;
}
Void display(){ System.out.println(id+“
”+name);}
Public static void main(){
student s=new student(1,”karan”);
s.display();} }
this keyword
this is a reference variable that refers to the
current object.
 this can be used to refer current class
instance variable.
 this can be used to invoke current class
constructor
 Used to invoke current class method
(implicitly)
 this can be passed as an argument in the
constructor call
 this can be passed as an argument in the
method call.
 this can also be used to return the current
class instance
Class student(){
Int id;
String name;
student(int id, string name) { id=id;
name=name; }
Void display(){
system.out.println(id+“ ”+name);}
Public static void main(){
student s=new student(1,”karan”);
s.display();} }
In this example , parameter and
instance variables are same that is
why we are using this keyword to
distinguish between local and
instance variable.
student(int id, string name)
{
this.id=id;
this.name=name;
}
this keyword used
for current class
instance variable
and constructor
Class student(){
Int id;
String name;
Student();{System.out.println(“default”
);}
student(int id, string name) {
this();
this(id, name);
this.id=id; this.name=name; }
Void display(){ System.out.println(id+“
”+name);}
Public static void main(){
student s=new student(1,”karan”);
s.display();} }
Garbage
collection and its
advantages
Garbage collection is a process of
reclaiming the runtime unused memory
automatically i.e destroying unused
objects.
 It makes java memory efficient
because it removes the unreferenced
objects from heap.
 It is automatically done by the
garbage collector so we don’t need to
make extra efforts.
Sometimes an object will need to perform
some action when it is destroyed.
For example, if
an object is holding some non-Java resource
such as a file handle or character font, then
you
might want to make sure these resources are
freed before an object is destroyed.
By using finalization, you can
define specific actions that will occur when
an object is just about to be reclaimed by the
garbage collector.
purpose of
finalize( )
method
 The finalize() method is invoked each
time before the object is garbage
collected.
 This method can be used to perform
cleanup processing.
 This method is defined in object class
as:
Protected void finalize()
{
}
You will specify those actions that
must be performed before an object is
destroyed.
finalize( )
method
Ppt on java basics1

More Related Content

PPTX
Ppt on java basics
PPTX
Control statements in java
PPTX
Lecture - 5 Control Statement
PPTX
Control structures in java
PDF
Java Programming - 04 object oriented in java
PPTX
Control flow statements in java
PDF
Java conditional statements
PDF
Generics and collections in Java
Ppt on java basics
Control statements in java
Lecture - 5 Control Statement
Control structures in java
Java Programming - 04 object oriented in java
Control flow statements in java
Java conditional statements
Generics and collections in Java

What's hot (20)

PPTX
Chapter 2 : Programming with Java Statements
PPT
Control statements in java programmng
PPT
Java control flow statements
PPTX
java programming- control statements
PPTX
Looping statements
PPTX
Java Decision Control
PPT
Jdk1.5 Features
PDF
PLSQL CURSOR
PPT
Java adapter
PPTX
Keywords of java
ODP
Synapseindia reviews.odp.
PPTX
Loop control statements
PPTX
Std 12 Computer Chapter 7 Java Basics (Part 2)
PPTX
Decision statements
PPT
Javatut1
PPT
Java Tut1
PDF
Programming in Java: Storing Data
PPT
Chapter 8 - Exceptions and Assertions Edit summary
PPT
M C6java3
Chapter 2 : Programming with Java Statements
Control statements in java programmng
Java control flow statements
java programming- control statements
Looping statements
Java Decision Control
Jdk1.5 Features
PLSQL CURSOR
Java adapter
Keywords of java
Synapseindia reviews.odp.
Loop control statements
Std 12 Computer Chapter 7 Java Basics (Part 2)
Decision statements
Javatut1
Java Tut1
Programming in Java: Storing Data
Chapter 8 - Exceptions and Assertions Edit summary
M C6java3
Ad

Viewers also liked (16)

PPT
ANDROID FDP PPT
PDF
Java ppt Gandhi Ravi (gandhiri@gmail.com)
PPS
Introduction to class in java
PPT
Oop java
PPTX
Classes, objects in JAVA
PDF
29 Essential AngularJS Interview Questions
PPT
Java Basics for selenium
PPTX
java Basic Programming Needs
PPT
Exception handling
PPT
String handling session 5
PPT
Java interfaces
PPT
Java packages
PPTX
Class object method constructors in java
PPTX
Method overloading and constructor overloading in java
PPTX
Constructor in java
PPTX
Constructor ppt
ANDROID FDP PPT
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Introduction to class in java
Oop java
Classes, objects in JAVA
29 Essential AngularJS Interview Questions
Java Basics for selenium
java Basic Programming Needs
Exception handling
String handling session 5
Java interfaces
Java packages
Class object method constructors in java
Method overloading and constructor overloading in java
Constructor in java
Constructor ppt
Ad

Similar to Ppt on java basics1 (20)

PDF
java notes.pdf
PPTX
Lecture - 3 Variables-data type_operators_oops concept
PDF
Programming in C Session 1
PPT
Java teaching ppt for the freshers in colleeg.ppt
PPT
Java Tutorial
PPT
Java tut1
PPT
Tutorial java
PPS
Programming in Arduino (Part 2)
PPTX
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
PPT
Java_Tutorial_Introduction_to_Core_java.ppt
PPT
Java Tutorial
PPT
Java tut1 Coderdojo Cahersiveen
PPT
Java tut1
PPT
Java tut1
PPT
Java Tutorial | My Heart
PPT
Core java
PPT
Java tutorial PPT
PPT
Java tutorial PPT
PPTX
Java fundamentals
java notes.pdf
Lecture - 3 Variables-data type_operators_oops concept
Programming in C Session 1
Java teaching ppt for the freshers in colleeg.ppt
Java Tutorial
Java tut1
Tutorial java
Programming in Arduino (Part 2)
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Java_Tutorial_Introduction_to_Core_java.ppt
Java Tutorial
Java tut1 Coderdojo Cahersiveen
Java tut1
Java tut1
Java Tutorial | My Heart
Core java
Java tutorial PPT
Java tutorial PPT
Java fundamentals

Recently uploaded (20)

PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
A Presentation on Artificial Intelligence
PPTX
Cloud computing and distributed systems.
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Empathic Computing: Creating Shared Understanding
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
NewMind AI Weekly Chronicles - August'25 Week I
The Rise and Fall of 3GPP – Time for a Sabbatical?
Per capita expenditure prediction using model stacking based on satellite ima...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
A Presentation on Artificial Intelligence
Cloud computing and distributed systems.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Advanced methodologies resolving dimensionality complications for autism neur...
Understanding_Digital_Forensics_Presentation.pptx
MYSQL Presentation for SQL database connectivity
Building Integrated photovoltaic BIPV_UPV.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Empathic Computing: Creating Shared Understanding

Ppt on java basics1

  • 3. One- dimensional array Declaring the array A list of items that can be given one variable name using only one subscript and such a variable is called one scripted variable or one dimensional array. Form1 : type arrayname[]; Form2: type [] arrayname; Ex: int num[]; float avg[]; int[] counter; float[] marks; Note : we don’t enter size of the array in declaration.
  • 4. Creation of array After we declare the array we need to create it in the memory Java allows us to create arrays using new operator only Syntax : arrayname=new type[size]; Ex : number= new int[5]; avg=new float[10]; It is possible to combine declaration and creation int number=new int[5];
  • 5. Initialization of arrays Syntax : arrayname[subscript]=value; Ex : number[0]=10; number[1]=20; Note :java creates the starting index with 0 and end with one less than the size of the array. type arrayname={list of values}; Ex: int num[]={10,20,30,40}; int a[]={1,2,3}; int b[]; b=a;
  • 6. Assigning one arrays to another. class demo12 { public static void main(String[] args) {int[] a=new int[5]; a[0]=211;a[1]=10;a[2]=12; a[3]=21;a[4]=100; int[] b=new int[5]; b=a; System.out.println("array of b is:"+b);}}
  • 7.  In java , all arrays store the allocated size in a variable named length.  We can obtain the length of array ‘a’ by a.length.  Ex : int arraylength=a.length Array length
  • 8. public class JavaArrayLengthExample { public static void main(String[] args) { String[] toppings = {"cheese", "pepperoni", "black olives"}; int arrayLength = toppings.length; System.out.format("The Java array length is %d", arrayLength); } } Output: The Java array length is 3
  • 9. Two- dimensional arrays 310 275 365 210 190 325 405 235 240 260 300 380 [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2] [3][0] [3][1] [3][2]
  • 10. int myarray[][]; myarray=new int [5]; int myarray[][]=new int [5]; Creating Two- dimensional arrays
  • 11. //Demonstrating two dimensional array class Multable { final static int ROWS=10; final static int COLUMNS=10; public static void main(String args[]) { int product[][]=new int[ROWS][COLUMNS]; int rows,columns; System.out.println(“2’s multiplication table is "); System.out.println(" "); int i,j; for(i=2;i<=ROWS;i++) { for(j=1;j<COLUMNS;j++) { product[i][j]=i*j; System.out.println(“ " +i+"*"+j+"="+ product[i][j]); } System.out.println(" "); } } } Output: 2’s multiplication table is 2*1=2 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18
  • 12. Beyond two dimensions, you can create an array variable that represents various lists, each list would contain various internal lists, and each internal list would contain its own components. This is referred to as a multidimensional array. One of the rules you must follow is that, as always, all members of the array must be of the same type. variable size arrays or Multi- dimensional array
  • 13. Java treats multidimensional arrays as “array of arrays”. When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension. You can allocate the remaining dimensions separately. For example, this following code allocates memory for the first dimension of twoD when it is declared. It allocates the second dimension manually. int twoD[][] = new int[4][]; twoD[0] = new int[5]; twoD[1] = new int[5]; twoD[2] = new int[5]; twoD[3] = new int[5]; Creating variable size arrays
  • 14. // Demonstrate a three-dimensional array of 3 by 4 by 5. class ThreeDMatrix { public static void main(String args[]) { int threeD[][][] = new int[3][4][5]; int i, j, k; for(i=0; i<3; i++) for(j=0; j<4; j++) for(k=0; k<5; k++) threeD[i][j][k] = i * j * k; for(i=0; i<3; i++) { for(j=0; j<4; j++) { for(k=0; k<5; k++) System.out.print(threeD[i][j][k] + " "); System.out.println(); } System.out.println(); } } } Output: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 0 0 0 0 0 2 4 6 8 0 4 8 12 16 0 6 12 18 24
  • 16. Any language uses control statements to cause the flow of execution to advance and branch based on the state of the program. Why do we need control statements?
  • 18.  Selection : to choose different paths of execution based on outcome or state of the variable.  Iterative : to repeat one or more statements.  Jump : to execute in non- linear fashion. Control Statements categories
  • 19. If statement is conditional branch statement. If Syntax: if(condition)statement1; else statement2; Ex : if(a>b)a=0; else b=0; Java’s selection statements oIf oswitch
  • 20. Switch is multi-way branch statement. Syntax : switch(expression){ Case value1: //statement sequence; break; Case value2: //statement sequence; break; default: //default statement sequence} Switch case
  • 21. Java’s iterative statements o while o do-while o for Iterative statements create what we commonly call loops which repeatedly executes the same set of instructions until a termination condition is met. while syntax: While(condition){ //body of loop }
  • 22. If the conditional expression controlling a while loop is initially false , then the body of the loop will not be executed at all. Sometimes it is desirable to execute the body of loop at least once even if the conditional expression is false. Condition is checked at the end of the loop. syntax: do{ //body of loop }while(condition); do- while case
  • 23. Syntax: for(initialization ; condition ; iteration) { //body of loop } When loop starts the initialization portion of the loop executes . Here initialization expression is executed only once. Next condition is evaluated. If the condition is true the body of the loop is executed. If false then loop terminates. Then iteration is executed i . e increments or decrements the loop control variable for loop case
  • 24. Used to transfer control to another part of your program Break statement has 3 uses: 1. Terminates a statement sequence in switch statement 2. To exit a loop 3. Civilized form of goto Java’s jump statements o break o continue o return
  • 25. // 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."); } } } break as civilized form of goto
  • 26. continue jump statement Skips the current iteration of a for , while or do-while loop. The unlabeled form skips to the end of the innermost loop’s body and evaluates Boolean expression that controls the loop. break leaves the loop. continue jumps to the next iteration.
  • 27. 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. // Demonstrate return. class Return { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if(t) return; // return to caller System.out.println("This won't execute."); } } The output from this program is shown here: Before the return. Return jump statement
  • 29. Class fundamentals : General form of class Class syntax: Class classname{ type instancevariable1; type instancevariable2; Type methodname1(parameter list){//body of method} Type methodname2(parameter list){//body of method}
  • 30. Class name convention class name should be nouns , in mixed cases with the first letter of each internal word capitalized. Ex : class CamelCase{ }
  • 32. what is instance variable?  Instance variables are declared in a class, but outside a method, constructor or any block.  When a space is allocated for an object in the heap, a slot for each instance variable value is created.  Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
  • 33. instance variable example Public class vehicle { //instance variables of class private int doors; private int speed; private string color; }
  • 34. what is class/static variable? They begins their life when first class loaded into memory and ends when class is unloaded i . e they remain in memory till class exist, so these variables often called Class variables.  There only one copy of these variables exist These variables are having highest scope that is they can be accessed from any method/ block in a class
  • 35. what is local variable? local variables are declared anywhere inside method. their life is started point they declared / initialized and ends when method completes.
  • 36. Example of types of variables public class Variables { static int staticVariable = 1; int instanceVariable = 2; public void methodName(int methodParameter) { int methodLocalVariable = 3; if (true) { int blockVariable = 4; } } }
  • 38. Objects are conceptually similar to real-world objects they too consist of state and related behavior. object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. What is an object?
  • 39. Declaring objects Box mybox=new Box(); This statement has 2 steps: 1. Box mybox; //mybox is reference variable 1. mybox= new Box(); //allocate a box object
  • 40. Declaring objects class Box { int width; int height; int depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); int vol; // assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } }
  • 41. Assigning object reference variable Box b1=new box(); Box b2=b1; //b1 = null; Here, b1 has been set to null, but b2 still points to the original object Note : When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference. b2 b1 Width Height Depth
  • 42. Introducing methods Why use methods? Methods are how we communicate with objects. When we call or invoke a method we are asking the objects to carry out a task  For reusable code  To simplify  For top-down programming  To create conceptual units  To parameterize code
  • 43. More generally, method declarations have six components, in order: 1.Modifiers—such as public, private, and others you will learn about later. 2.The return type—the data type of the value returned by the method, or void if the method does not return a value. 3.The method name—the rules for field names apply to method names as well, but the convention is a little different. 4.The parameter list in parenthesis—a comma- delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. 5.An exception list—to be discussed later. 6.The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here. Method components
  • 44. Method name convention Method name should be verbs , in mixed case with the first letter lowercase , with the first letter of each internal word capitalized. Ex : class CamelCase{ Void runFast() }
  • 45. General form of methods type-name(parameters list) { //body of the method } Ex: void volume() { System.out.println(“volume is”); System.out.println(width*height* depth); ]
  • 46. Constructor and its purpose Constructor is a special type of method that is used to initialize the object. It 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.
  • 47. Rules for creating constructors 1. Constructor name must be same as it class name 2. Constructor must have no explicit return type.
  • 48. Types of Constructors 1. Default constructor(no-arg constructor) 2. Parameterized constructor. A constructor that has no parameters is known as default constructor. Class bike(){ Bike(){System.out.println(“bike constructor”);} Public static void main(){ bike b=new bike(); } }
  • 49. Parameterized constructors A constructor that has parameters is known as parameterized constructor. Class student(){ Int id; String name student(int i, string n) { id=i; name=n; } Void display(){ System.out.println(id+“ ”+name);} Public static void main(){ student s=new student(1,”karan”); s.display();} }
  • 50. this keyword this is a reference variable that refers to the current object.  this can be used to refer current class instance variable.  this can be used to invoke current class constructor  Used to invoke current class method (implicitly)  this can be passed as an argument in the constructor call  this can be passed as an argument in the method call.  this can also be used to return the current class instance
  • 51. Class student(){ Int id; String name; student(int id, string name) { id=id; name=name; } Void display(){ system.out.println(id+“ ”+name);} Public static void main(){ student s=new student(1,”karan”); s.display();} } In this example , parameter and instance variables are same that is why we are using this keyword to distinguish between local and instance variable. student(int id, string name) { this.id=id; this.name=name; }
  • 52. this keyword used for current class instance variable and constructor Class student(){ Int id; String name; Student();{System.out.println(“default” );} student(int id, string name) { this(); this(id, name); this.id=id; this.name=name; } Void display(){ System.out.println(id+“ ”+name);} Public static void main(){ student s=new student(1,”karan”); s.display();} }
  • 53. Garbage collection and its advantages Garbage collection is a process of reclaiming the runtime unused memory automatically i.e destroying unused objects.  It makes java memory efficient because it removes the unreferenced objects from heap.  It is automatically done by the garbage collector so we don’t need to make extra efforts.
  • 54. Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or character font, then you might want to make sure these resources are freed before an object is destroyed. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. purpose of finalize( ) method
  • 55.  The finalize() method is invoked each time before the object is garbage collected.  This method can be used to perform cleanup processing.  This method is defined in object class as: Protected void finalize() { } You will specify those actions that must be performed before an object is destroyed. finalize( ) method