MOD1 PPT-chap 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 139

MODULE 1

AN OVERVIEW OF JAVA
OOP(Object Oriented Programming)
• Object oriented programming (OOP) is the core of
Java programming.
• While object-oriented programming is about
creating objects that contain both data and
methods.
• Java is a general purpose, object- oriented
programming language developed by Sun
Microsystems.
• It was invented by James Gosling and his team and
was initially called as Oak.
Two Paradigms:
• Every program contains 2 components code and data.
• Two approaches are there to solve the problem and in
program writing: Procedure oriented and object
oriented.
Procedure Oriented:
• Procedure oriented programs are written based on
―whats happening‖ around, where the code acts on
data. Ex: C etc
Object Oriented:
• Object oriented programs are written based on ―Who
is being affected‖ around, which manages the
increasing complexity.
• Ex: C++, JAVA, Small Talk etc
• C
Class a{
Printf(“Welcome”); // Procedure Oriented:
}

• C++
Class a{
Cout<<welcome; //Object Oriented:

}
The Three OOP:
The three important features of OOP are:

• Encapsulation
• Inheritence
• Polymorphism
Encapsulation
• It is a process of wrapping up the data
members along with related data handlers
method is called Encapsulation.
• Wrapping up the data members and data
handlers method means we are grouping both
as a single unit. In Java, we group or wrap
both inside the Class, so Class is a single unit
that consists of data members as well as
methods.
Ex
Ex
Note:
This keyword
• this can be used to refer current class instance variable.
• this can be used to invoke current class method
(implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance
from the method.
Inheritence:
• Inheritence is the process by which one object
acquires the properties of another object. This
is important as it supports the concept of
hierarchical classification.
• By the use of inheritence, sub class derived
from the parent class or base class.
• Ex: A child inheriting properties from parents
• Single Inheritance:
• Multiple Inheritance:
• Multilevel Inheritance
• Hierarchical Inheritance:
• Hybrid Inheritance:
Single Inheritance:
Multilevel Inheritance
Deriving the class from another derived class:
class C extend class B and class C extend class A
Parent class is inherited by many sub classes
Multiple Inheritance
Deriving the class from more than one direct base class
Hybrid Inheritance
More than one kind of the inheritance is observed
Polymorphism
• polymorphism refers it is having same name and
multiple forms
• Polymorphism (meaning many forms)
• Polymorphism uses those methods to perform
different tasks. This allows us to perform a single
action in different ways.
• It performs based on arguments
• Ex: “+”‖ can be used for addition of 2 numbers and
also concatenation of 2 strings.
System.out.println(2+4); // outputs 6 as answer
System.out.println(“Hello‖” +”vandana‖”); // outputs
Hello vanadana as answer
• 2 or more methods in a same class have the
same name but different parameter//
overloading
Method overloading
method add(float a,float b)
{
Return a+b
}
method add(int a,int b,int c)
{
Return a+b+c
}
method add(string a,string b)
{
Return a+b
• Name and parameters are same in the
superclass and child class // overriding
Operator overloading
Operator + (int a,int b)
{
Return a+b
}
Operator + (string a,string b)
{
Return a+b
}
• Child class has the same method as declared
in the parent class.// method overriding
override
Class A{
Method add(int a,int b)
{
Return a+b
}
Class B extend class A{
Override Method add( int x,int y){
Return x+y
}
}
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Output:
The animal makes a sound
The pig says: wee wee
The dog says: bow wow
Object:

• An object is an instance of class.


• An object can be any real world entity.
• An entity that has state and behavior is known
as an object e.g., chair, bike, marker, pen, table,
car, etc.
• Ex: an animal, bank, human, box, fan etc
• An object is a software bundle of related state
and behavior.
Class:

• A class is a blueprint or prototype from which


objects are created.
• A class is a group of objects which have
common properties.
• It is a template or blueprint from which objects
are created. It is a logical entity.
• A class is a user defined data type.
• 2 type: user and pre define(already defined in
the java class libraries)
Class and object
Abstraction:
• Abstraction is a process of hiding the
implementation details and showing only
functionality to the user.
• Ex: a database system hides certain details of
how data is stored and created and
maintained.
Abstract Class
• A class which contains the abstract keyword in its
declaration is known as abstract class.
• Abstract classes may or may not contain abstract methods,
i.e., methods without body ( public void get(); )
• But, if a class has at least one abstract method, then the
class must be declared abstract.
• If a class is declared abstract, it cannot be instantiated.
• Abstract class: is a restricted class that cannot be used to
create objects (to access it, it must be inherited from
another class).

Abstract method:
can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
• The pig says: wee wee
Zzz
ex
A First Simple Program
1. Open the notepad and type the above program
2. Save the above program with .java extension, here file name and
class name should be same,
ex: Example.java
3. Open the command prompt and Compile the above program
javac
Example.java
From the above compilation the java compiler produces a
bytecode(.class file)
4. Finally run the program through the
interpreter java Example.java

Output of the program:


Welcome to Programming in Java
Note: Java is case-sensitive
Compiling the program
• To compile the program, execute the compiler ―”javac‖”,
specifying the name of the source file on the command line as
shown below
• C:\> javac Example.java
• The ―javac: compiler creates a file called ―Example.class‖ that
contains the bytecode version of the program.
• To run the program, we must use the java interpreter called
“java”‖. To do so we pass the class name ―Example‖ as a
command-line argument as shown below

C:\> java Example


• When you run the program we get the output:

Welcome to Programming in Java


• Description: (1) Class declaration: ―class Example‖
declares a class, which is an object- oriented construct.
• (2) Opening braces: Every class definition of Java starts
with opening braces and ends with matching one.
• (3) The main line: the line ― public static void
main(String args[]) ― defines a method name main.
Java application program must include this main. This is
the starting point of the interpreter from where it starts
executing.
• (4) Public: This key word is an access specifier that
declares the main method as unprotected and
therefore making it accessible to the all other classes.
• (5) Static: Static keyword defines the method as one
that belongs to the entire class and not for a particular
object of the class. The main must always be declared a
static.
• (6) Void: the type modifier void specifies that the
method main does not return any value.
• (7) The println: It is a method of the object out of system
class. Display the content on console.
• It is similar to the printf or cout of c or c++. This always
appends a newline character to the end of the string i.e,
any subsequent output will start on a new line.
A Second Short Program
/* This is a short example Name of file : Example2.java */

class Example2//declaration
{
public static void main(String args[]) //define main method
{
int n=3; //initialized
System.out.println(“the value of n is “+n);//input the line
n=n+5; //assigned the value(appending or add)
System.out.print(“ the new value is”); //display ,newline
System.out.println(n); //display
}
}
Output: the value of n is 3//o/p
Two Control Statements
• Here in this chapter initially we focus on two
control statements if and for loop , the detailed
control statements will be discussed in module 2.
if statement
• The if- statement is the most basic of all the
control flow statements.
• It tells your program to execute a certain section
of code only if a particular test evaluates to true.
• Here is the general form of the if statement:
if (condition) :
statement;
• Here the condition is Boolean expression.
• If the condition is true then the statement is
executed, if false then statement will be
skipped.
Example:

class Example
{
public static void main(String args[])
{
int a=5;
if(a>0)
System.out.println(“a is positive number‖”);
System.out.println(“End of program”‖);
}
}
class If Sample {
public static void main(String args[]){
int x, y;
x = 10;
y = 20;
if(x < y)
System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x > y)
System.out.println("x now greater than y"); // this won't display anything
if(x == y)
System.out.println("you won't see this");
}}
The output generated by this program is shown here:
x is less than y
x now equal to y
x now greater than y
The for loop
• The for loop is similar to that of C/C++
• Here is the general form of the traditional for
statement:
for(initialization; condition; iteration)
{
//body
}
• Initialization sets the loop control variable to
initial value.
• Condition is a Boolean expression which tests
the loop
• Iteration expression tells how the control
variable has to change at each iteration.
Generally the increment or decrement
operator is used to perform iteration.
Example:
class Example
{
public static void main(String args[])
{
int a;
for(a=0;a<5;a++)
System.out.println(a);
System.out.println(“ End of program”);
}
}

o/p:
Output: 0
1
2
3
4
Using blocks of code
• Java supports code blocks - which means that two
or more statements are grouped into blocks of
code.
• Section of the code enclosed in curly brackets{}.
• Opening and closing braces is used to achieve this.
• Each block is treated as logical unit.
• Whenever two or more statements has to be
linked blocks can be used.
class Example1
{
public static void main(String args[])
{
int x=10;
Int y=20;
System.out.println(“The answer is”);
System.out.println(x+y);
System.out.println(“End program”);
//A code block enclosing a multiple statement
Lexical issues:
• A lexical token may consist of one or more
characters, and every single character is in
exactly one token.
• The tokens can be keywords, comments,
numbers, white space, or strings. All lines
should be terminated by a semi-colon (;).
• Java programs are a collection of whitespace,
identifiers, literals, comments, operators,
separators, and keywords.
Whitespace:
• Java is a free from language- means no need
to follow any indentation rules.
• It returns T or F/ Boolean value
• Whitespace is a space, tab, or newline
• \b
• \n
• \t
Java character set:
• The smallest unit of Java language are its
character set used to write Java tokens.
Key Words:

• Keyword means Reserved terms that have a special


function and set of defination in java.
• Java program is basically a collection of classes. A class
is defined by a set of declaration statements and
methods containing executable statements.
• Smallest individual units of programs are known as
tokens.
• Java language includes five types of tokens.
They are
(a) Reserved Keyword
• (b) Identifiers
• (c) Literals.
• (d) Operators
Reserved keyword:
• Java language has 50 words as reserved
keywords. They implement specific feature of
the language.
• The keywords combined with operators and
separators according to syntax build the Java
language
Identifiers:

Identifiers are programmer-designed token used for naming


classes methods variable, objects, labels etc. The rules for
identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.
5. Name of all public method starts with lowercase.
6. In case of more than one word starts with uppercase in next
word.
7. All private and local variables use only lowercase and
underscore.
8. All classes and interfaces start with leading uppercases.
9. Constant identifier uses uppercase letters only
• Example for valid identifiers:
Var_1, count, $value etc

Example for invalid identifiers:


6name, var@value, my/name etc
Literals:
• Synthetic representation of boolean, charecter, numeric or
string data.
• Literals in Java are sequence of characters that represents
constant values to be stored in variables. Java language
specifies five major types of Literals.
• They are:
1. Integer Literals. (int)
2. Floating-point Literals.(float)
3. Character Literals. (char)
4. String Literals. (string)
5. Boolean Literals.(boolean)
Operators:
• An operator is a symbol that takes one or
more arguments and operates on them to
produce an result.
• Add,Sub,Mul,Div ,mod
Separators:

• Separators are the symbols that indicates where group of


code are divided and arranged.
• Some of the operators are:
Comments:
Java supports 3 styles of comments
• Multiline comment: this type of comment begins with /*
and ends with */
Ex: /* Welcome to Java Programming */
• Single line comments: this type of comment begins with //
and ends at the end of current line
Ex: // Welcome to java Programming
• Documentation Comment:
This type of comment is used to produce an HTML file that
documents your program. The documentation comment
begins with /** and ends with */
Ex: /** Welcome to java Programming*/
Java Class libraries:
Java environment has several built in class libraries. Java
standard library includes hundreds of classes and methods
grouped into several functional packages.

Most commonly used packages are:


(a) Language support Package.
(b) Utilities packages.
(c) Input/output packages
(d) Networking packages
(e) AWT packages.
(f) Applet packages
1) java.lang: Contains language support classes(e.g
classed which defines primitive data types, math
operations). This package is automatically imported.
2) java.io: Contains classed for supporting input /
output operations.
3) java.util: Contains utility classes which implement
data structures like Linked List, Dictionary and
support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the
components for graphical user interfaces (like
button , ;menus etc). Abstract Window Toolkit (AWT)
6) java.net: Contain classes for supporting
networking operations.
Data types
• Data types specify the different sizes and
values that can be stored in the variable.
There are two types of data types in Java:
• Primitive data types: The primitive data types
include boolean, char, byte, short, int, long,
float and double.
• Non-primitive data types: The non-primitive
data types include Classes, Interfaces, and
Arrays.
Data types
• The various data types supported in java is as follows
Java defines eight primitive types of data:

• byte, short, int, long, char, float, double, and


boolean.
• The primitive types represent single values—
not complex objects.
• Bit(smallest unit of the data)
• Byte( 8 bite)
Integers
• Java defines four integer types: byte, short,
int, and long.
• All of these are signed, positive and negative
values.
• Java does not support unsigned
• Integer represented by int sign
• Ex: int i=1;
byte
• The smallest integer type is byte.
• Size is 1
• This is a signed 8-bit type that has a range from –128
to127.
• Byte variables are declared by use of the byte
keyword.
For example,
• the following declares two byte variables called b and
c:
• byte b, c;
short
• short is a signed 16-bit type.
• size is 2
• It has a range from –32,768 to 32,767.
• It is probably the least-used Java type
• Here are some examples of short variable
declarations:
short s;
short t;
Floating-Point Types
• Floating-point numbers, also known as real
numbers, are used when evaluating
expressions that require fractional precision.
• There are two kinds of floating-point types,
float and double, which represent single- and
double-precision numbers, respectively
float
• The type float specifies a single-precision
value that uses 32 bits of storage.
• Ex float f=2.1;// 32 bits
double
• Double precision, as denoted by the double
keyword, uses 64 bits to store a value.
• Ex: double df=23.400;
Characters
• In Java, the data type used to store characters is
char.
• char in Java is not the same as char in C or C++.
• In C/C++, char is 8 bits wide. This is not the case in
Java. Instead, Java uses Unicode to represent
characters.
• ex: char c=‘a’,’b’,’c’;
• String str=“ram”,”jai”;
• Thus, in Java char is a 16-bit type. The range of a
char is 0 to 65,536. There are no negative
Booleans:
• Java has a simple type called boolean for
logical values.
• It can have only one of two possible values.
They are true or false.
Literals:

• A constant value in Java is created by using a literal


representation of it. literal is a notation that
represents a fixed value in the source code.
• literals are the constant values that appear directly
in the program
There are 5 types of literals.
• Integer Literals.
• Floating-point Literals.
• Character Literals.
• String Literals.
• Boolean Literals
Integer literals:
• Any whole number value is an integer literal.
• These are all decimal values describing a base 10 number.
• There are two other bases which can be used in integer
literal,
• octal( base 8) where 0 is prefixed with the value,
• hexadecimal (base 16) where 0X or 0x is prefixed with the
integer value
Example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
Floating point literals:
• The default type when you write a floating-
point literal is double
• However, the suffix F (or f) is appended to
designate the data type of a floating-point
literal as float.
• We can also specify a floating-point literal in
scientific notation using Exponent (short E
ore), for instance: the double literal 0.0314E2
is interpreted as:
• Example:
• 0.0314 *10² (i.e 3.14).
• 6.5E+32 (or 6.5E32) Double-precision floating-
point literal
• 7D Double-precision floating-point literal .
• 01f Floating-point literal
Character literals:
• char data type is a single 16-bit Unicode character.
• We can specify a character literal as a single
printable character in a pair ofsingle quote
characters such as 'a', '#', and '3'.
• The ASCII character set includes 128 characters
including letters, numerals, punctuation etc.
• Below table shows a set of these special
characters.
Boolean Literals:
• The values true and false are treated as literals in Java
programming.
• When we assign a value to a boolean variable, we can
only use these two values.
• Unlike C, we can't presume that the value of 1 is
equivalent to true and 0 is equivalent to false in Java.
• We have to use the values true and false to represent
a Boolean value
• Example
• boolean chosen = true;
String Literal
• The set of characters in represented as String
literals in Java.
• Always use "double quotes" for String literals.
• Example: “hello world”-Java‖
ex
public class LiteralsExample
System.out.println(count);
{
System.out.println(floatVal);
public static void main(String args
System.out.println(cost);
[]) {
System.out.println(hexaVal);
int count = 987;
System.out.println(binary);
float floatVal = 4534.99f;
System.out.println(alpha);
double cost = 19765.567;
System.out.println(str);
int hexaVal = 0x7e4;
System.out.println(boolVal);
int binary = 0b11010;
System.out.println(octalVal);
char alpha = 'p';
System.out.println(stuName);
String str = "Java";
System.out.println(ch1);
boolean boolVal = true;
System.out.println("\
int octalVal = 067;
t" +"backslash literal");
String stuName = null;
System.out.println(ch2);
char ch1 = '\u0021';
}
char ch2 = 1456;
}
o/p
Variables:
• A variable is an identifier that denotes a storage
location used to store a data value.
• variable is a container which holds the value while
the Java program is executed
To declare one identifier as a variable there are certain
rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.
Types of variable
• String - stores text, such as "Hello". String values are
surrounded by double quotes
• int - stores integers (whole numbers), without
decimals, such as 123 or -123
• float - stores floating point numbers, with decimals,
such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes
• boolean - stores values with two states: true or false
Declaring Variable:

• To specify its name and characteristics.


type identifier [ = value][, identifier [= value] ...] ;

Syntax:
type variableName = value;

Example 1: int a,b,c; Declaring variable


int a = 3;
Float f=5.6;
System.out.println(a);
System.out.println(f);

Example 2:
String name = "John";
System.out.println(name);
Initializing a variable:
• followed by the variable name, followed by an
equal sign, followed by an expression.
• variable can be initialize in two ways.
They are
• (a) Initializing by Assignment statements.
• (b) Dynamic Initialisation
Initializing by assignment statements:
One variable can be initialize using assignment
statements.
• datatype: Type of data that can be stored in this
variable.
• variable_name: Name given to the variable.
• value: It is the initial value stored in the variable.
The syntax is : Variable-name = Value;
Example:
• int a=10,b,c=16;
• Double pi=3.147;
// Declaring float variable
float simpleInterest;

// Declaring and initializing integer variable


int time = 10, speed = 20;

// Declaring and initializing character variable


char var = 'h';
Dynamic initialization:
Java allows variables to be initialized dynamically, using expression
valid at the time variable is declared. (done at run time)

Example:
class Example {
public static void main(String args[])
{
double a=10, b=2.6;
double c=a/b;
System.out.println(“value of c is”+c);
}
}
Types of Variables in Java
Different types of variables
• Local Variables
• Instance Variables
• Static Variables
Local Variables
• A variable that is only accessible within a specific part of a
program.
• A variable defined within a block or method or constructor is
called a local variable.
• These variables are created when the block is entered, or the
function is called and destroyed after exiting from the block or
when the call returns from the function.
• The scope of these variables exists only within the block in
which the variables are declared, i.e., we can access these
variables only within that block.
• Initialization of the local variable is mandatory before using it in
the defined scope.
Example
// Java Program to implement
// Local Variables
import java.io.*;
class Local{
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Output
Local Variable: 10
2.Instance Variables
• Instance variables are non-static variables and are
declared in a class but outside of any method,
constructor, or block.
• This variable is created when an object is instantiated
and accessible to all constructor, methods or blocks in
the class.
• Initialization of an instance variable is not mandatory.
Its default value is dependent on the data type of
variable. For String it
is null, for float it is 0.0f, for int it is 0, for Wrapper
classes like Integer it is null, etc.
• Instance variables can be accessed only by creating
Example
// Java Program to demonstrate // Main Method
// Instance Variables public static void main(String[] args)
{
import java.io.*;
// Object Creation
class Instance{ Instance name = new Instance ();
// Declared Instance Variable // Displaying O/P
public String Pname; System.out.println(“Person name is: " +
public int i; name.Pname);
System.out.println("Default value for int
public Integer I; is: "+ name.i);
public Instance()
{ // toString() called internally
// initializing Instance Variable System.out.println("Default value for
Integer is: "+ name.I);
this.Pname = “Adya Jain";
}
} }
Output:
Person name is: Adya Jain
Default value for int is: 0
Default value for Integer is: null
3. Static Variables
• Static variables are also known as class variables.
• It is declared as static. Single copy of the copy is
created.
• A variable that has been allocated "statically",
meaning that its lifetime (or "extent") is the
entire run of the program.
• The difference is that static variables are
declared using the static keyword within a class
outside of any method, constructor, or block.
Exam p le

// Java program to demonstrate execution


// of static blocks and variables
class StaticVariable{ // static variable
static int a = m1();
static
{
System.out.println("Inside static block"); // static block
}
static int m1()
{
System.out.println("from m1"); // static method
return 20;
}
public static void main(String[] args)
{
System.out.println("Value of a : " + a); // static method(main !!)
System.out.println("from main");
Output
from m1
Inside static block
Value of a : 20
from main
The Scope and Lifetime of Variables
• Java allows variables to be declared within any block.
• A block is begun with an opening curly brace and ended by
a closing curly brace.
What is Scope of variable?
• Scope of variable defines how a specific variable is
accessible within the program or across classes. or
• Defines where a certain variable or method is accessible in
a program.
What is lifetime variable?
• The time during which a variable retains its value is known
as its lifetime. Or until the object stays in memory.
class Scope {
public static void main(String args[])
{
int x=10; // known to all code within main x = 10;
if(x == 10) // start new scope
{
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// x is still known here.
System.out.println("x is " + x);
}
}
Output
x and y: 10 20
x is 40
Type Conversion and casting
• It is often necessary to store a value of one
type into the variable of another type.
• Assigning a value of one type to a variable of
another type is known as Type Casting .
• Type casting can be done in two ways. In Java,
type casting is classified into two types,
1.Widening casting(Implicit)

• The two data types are compatible.


• When we assign a value of a smaller data type
to a bigger data type.
// Java Program to Illustrate Automatic Type Conversion
// Main class
class implicit{

// Main driver method


public static void main(String[] args)
{
int i = 100;
// Automatic type conversion
// Integer to long type
long l = i;
// Automatic type conversion
// long to float type
float f = l;
// Print and display commands
System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
o/p
• Int value 100
• Long value 100
• Float value 100.0
2.Narrowing casting(Explicitly done)
• This is useful for incompatible data types
where automatic conversion cannot be done.
• Here, the target type specifies the desired
type to convert the specified value to.
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Explicit casting:
double to int
System.out.println(myDouble);
System.out.println(myInt);
}
}
o/p
9.78
9
Widening or Automatic type conversion

• Widening conversion takes place when two


data types are automatically converted

• the two types are compatible


• the target type is larger than the source type
Example : public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l;
//no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
o/p
Int value 100
Long value 100
Narrowing or Explicit type conversion
• When you are assigning a larger type value to
a variable of smaller type, then you need to
perform explicit type casting.
Example :
public class Test {
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required System.out.println("Double
value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Output:
Double value 100.04
Long value 100
Int value 100
Automatic type promotion in expressions:
Type conversions also occurs in expressions.
Java automatically promotes each byte, short, or char operand
to int when evaluating an expression.
• byte b = 50; b = b * 2;
• // Error! Cannot assign an int to a byte!
the operands were automatically promoted to int when the
expression was evaluated, the result has also been promoted
to int. Thus, the result of the expression is now of type int,
which cannot be assigned to a byte without the use of a cast.
• byte b = 50; b = (byte)(b * 2);
• which yields the correct value of 100
• Java defines several type promotion rules that apply
to expressions. They are as follows:
• First, all byte, short, and char values are promoted
to int, as just described.
• Then, if one operand is a long, the whole
expression is promoted to long.
• If one operand is a float, the entire expression is
promoted to float.
• If any of the operands is double, the result is
double.
Arrays in Java Array
• which stores a fixed-size sequential collection
of elements of the same type.
• An array is used to store a collection of data,
but it is often more useful to think of an array
as a collection of variables of the same type.
Declaring Array Variables
• To use an array in a program, you must declare a
variable to reference the array, and you must
specify the type of array the variable can reference.
Here is the syntax for declaring an array variable:

Example:
Creating/Initializing Arrays:

• You can create an array by using the new operator


with the following syntax:
arrayRefVar = new dataType[arraySize];

The above statement does two things:


• It creates an array using new dataType[arraySize];
• It assigns the reference of the newly created array
to the variable
• arrayRefVar.RefVar = new dataType[arraySize];
1. Without assigning values
Declaring an array variable,
creating an array, and assigning the reference of
the array to the variable can be combined in
one statement, as shown below:
• dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:


• dataType[] arrayRefVar = {value0, value1, ..., value k};
• The array elements are accessed through the index.
Array indices are 0-based;
• they start from 0 to arrayRefVar.length-1.
Example:
• Following statement declares an array variable, myList,
creates an array of 10 elements of double type and assigns
its reference to myList:
double[] myList = new double[10];
• Following picture represents array myList. Here, myList
holds ten double values and the indices are from 0 to 9,
they start from 0 to arrayRefVar.length-1.
2. After the declaration of the array
• Array Initialization after Declaration (Using
Loops)
• We initialize the array after the declaration by
assigning the initial value to each element
individually.
• We can use for loop, while loop, or do-while
loop to assign the value to each element of
the array.
Example
Processing Arrays:
• When processing array elements, we often
use either for loop or for each loop because all
of the elements in an array are of the same
type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize
and process arrays:
class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < 4; i++)
{
System.out.println(myList[i] + " ");
}
}
Multidimensional Arrays
• Java does not support multidimensional
arrays.
• An array with more than one level or
dimension.Ex 2D array or 2 dimentional array.
• Matrix of rows and columns.
• int coords[] [] = new int[12] [12];
EX:
• coords[0] [0] = 1; coords[0] [1] = 2;
A few words about strings:
• Strings are the type of objects that can store the
character of values and in Java
• Java supports string type which is an object. It is
used to declare string variables
• Array of strings can also be declared.
• A string variable can be assigned to another string
variable.
• Example:1
• String demoString(“Ram”);
• String demoString = new String (“Ram”);
• String variable can also be used as argument.
Example:1
String name1=‖shree, name2;
Name2=name1; // sets name2 with value shree
System.out.println(name2);//string variable
passed as parameter
Example:2
String name = “Java";

You might also like