0% found this document useful (0 votes)
24 views81 pages

Java Programming

Uploaded by

bneelagund
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
24 views81 pages

Java Programming

Uploaded by

bneelagund
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 81

JAVA PROGRAMMING

18CS653
MODULE-1
AN OVERVIEW OF JAVA
TOPICS
1.1 Introduction to Java
1.2 Bytecode
1.3 The Java Buzzwords
Simple
Secure
Portable
Object-Oriented
Robust
Multithreaded
Architecture-Neutral
Interpreted and High Performance
Distributed
Dynamic
1.4 Object-Oriented Programming
1.4.1 Two Paradigms
1.4.2 Abstraction
TOPICS
1.5 The Three OOP Principles
1.6 A First Simple Program
Entering the Program
Compiling the Program
A Closer Look at the First Sample Program
1.7 Two Control Statements
1.7.1 The if Statement
1.7.2 The for Loop
1.8 Using Blocks of Code
1.9 Lexical Issues
1.9.1 Whitespace
1.9.2 Identifiers
1.9.3 Literals
1.9.4 Comments
1.9.5 Separators
1.10 The Java Keywords
TOPICS
1.11 Java Is a Strongly Typed Language
1.12 The Primitive Data Types
1.12.1 Integers
1.12.2 byte
1.12.3 short
1.12.4 int
1.12.5 long
1.13 Floating-Point Types
1.13.1 float
1.13.2 Double
1.14 Characters
1.15 Booleans
1.16 A Closer Look at Literals
1.16.1 Integer Literals .
1.16.2 Floating-Point Literals
1.16.3 Boolean Literals
1.16.4 Character Literals
1.16.5 String Literals
TOPICS
1.17 Variables
1.17.1 Declaring a Variable
1.17.2 Dynamic Initialization
1.17.3 The Scope and Lifetime of Variables
1.18 Type Conversion and Casting
1.18.1 Java’s Automatic Conversions
1.18.2 Casting Incompatible Types
1.19 Automatic Type Promotion in Expressions
1.19.1 The Type Promotion Rules
1.20 Arrays
1.20.1 One-Dimensional Arrays
1.20.2 Multidimensional Arrays
1.20.3Alternative Array Declaration Syntax
1.1 INTRODUCTION TO JAVA

Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan


at Sun Microsystems Inc. in 1991.
The initial name was Oak but it was renamed to Java in 1995.
Initially the idea was to develop Java language for digital devices such as
television, set-top box, remote etc. Later this idea was dropped and Java is
developed for internet programming.
James Gosling is considered the original developer of Java language. He is
also known as father of Java.
JDK Alpha and Beta was first released in 1995 and later various version of
JDK were released currently Java SE 20 was released in March 2023 and
Java SE 21 will be released in September 2023
INTRODUCTION TO JAVA

 Java is a general-purpose, high-level programming language that helps


programmers and developers to write a code once and run it anywhere

( WORA).
Java is the name of a beautiful island in Indonesia. It is also said that the
first coffee was named right here after java coffee.
JAVA PLATFORM EDITIONS

 Following are the different types of java platform editions


o Micro Edition – J2ME (Java ME)
o Standard Edition – J2SE (Java SE )
o Enterprise Edition – J2EE (Java EE )
o Java Card/Java FX.

Java Technology = Programming Language + Platform

Programming Language: Java programming language is a high-level


object-oriented language that has a particular syntax and style.
Java Platform :A Java platform is a particular environment in which Java
programming language applications run.
Every Platform consist of JVM and API
Java Virtual Machine is a program, for a particular hardware and software
platform, that runs Java technology applications.
Application Program Interface :An API is a collection of software
components that you can use to create other software components or
applications.
J2SE ( Java 2 Standard Edition) : is made up of API that provide Java's
fundamental programming features. It specifies all the aspects of Java
Programming from basic data types to high level classes for security, GUI,
Database Manipulations and Networking.
J2EE (Java 2 Enterprise Edition):The Java Enterprise Edition (Java EE)
was developed to expand the Java SE with the addition of a collection of
standards/specifications that describe frequently used features by commercial
applications. Features such as JSP, JSF, JPA and EJB were used .
J2ME ( Java 2 Micro Edition) : Java Micro Edition was developed to
facilitate mobile and embedded device applications.
Some examples of Java ME applications are given below:
Calculator for Mobile which demonstrates the functionality of multi-
threading.
GPIO (General Purpose Input Output) applications.
Location APIs, etc
JavaFX: JavaFX is a platform that uses a simple user-interface API to
enable the development of rich online applications, GUI applications, and
Desktop applications. It was created in Java to take the place of Swing as the
default GUI library.
APPLICATIONS DEVELOPED USING JAVA

Following are the different types of Applications that can be developed.


o Standalone Applications
o Web Applications
o Enterprise Applications
o Mobile Applications
 Standalone Applications : Standalone applications are those applications
that runs on separate computer.
Example: Media player, antivirus, Paint, POS Billing software, etc.

Web Applications: Web Applications are the client-server software


application which is run by the client.
Example: mail, e-commerce website, bank website etc.
Enterprises Applications : Enterprise application is middleware applications.
To use software and hardware systems technologies and services across
the enterprises.
Example: e-commerce, accounting, banking information systems etc.

Mobile Applications: For mobile applications, Java uses ME or J2ME


framework. This framework are the cross platform that runs applications
across phones and smartphones. Java provides a platform for application
development in Android too.
Example: WhatsApp, Xender etc.
JDK -JAVA DEVELOPMENT KIT

Vs

JVM- JAVA VIRTUAL MACHINE

Vs

JRE- JAVA RUNTIME ENVIRONMENT


JDK -JAVA DEVELOPMENT KIT
JDK is a superset of JRE, it contains everything that JRE has along with
development tools such as compiler, debugger etc.
1. JDK stands for Java Development Kit. To install Java on your system, you
need to first install JDK on your system.
2. JDK contains the tools that you need, in order to write and execute
java programs.
3. JDK consists of Private JRE, JVM, compiler, Java application launcher,
Appletviewer, etc. It also provides the Standard Edition (SE) of java API.
JRE – JAVA RUNTIME ENVIRONMENT
JRE stands for Java Runtime Environment.
It provides runtime environment for java applications.
You need JRE in order to run java programs. If you are not a developer and not
writing java programs, you do not need JDK but you still need JRE to run java
programs.
All the JDK already comes with JRE so you do not need to download and
install it separately.
JRE contains set of libraries and other files that JVM uses at runtime
JVM – JAVA VIRTUAL MACHINE
 Java Virtual Machine resides in your computer. ( that is every computer has
JVM)
 JVM makes it possible to run java code on any machine, it is the JVM that
makes java truly platform independent.
It also allows to run java applications on cloud platforms.
JDK and JRE both of these contain JVM.
JVM is an interpreter as it executes the java code line by line.
JVM converts the bytecode into machine code.
JVM is platform independent as JVM doesn’t depend on the hardware and
operating system of the machine.
Difference between JDK JRE and JVM
1.2 BYTECODE
Bytecode is a highly optimized set of instructions designed to be executed by
the Java run-time system, which is called the Java Virtual Machine (JVM).

Advantage: Source code need not be recompiled again and again


1.3 JAVA BUZZ WORDS/ FEATURES OF JAVA

The java features are also known as Java Buzz Words

Following are the features of java

1) Simple
2) Secure
3) Portable
4) Object-oriented
5) Robust
6) Multithreaded
7) Architecture-neutral
8) Interpreted
9) High performance
10) Distributed
11) Dynamic
1) Simple : Java is a very simple programming language, it is easy to learn,
read and write in Java. The syntax of Java is clean and easy to understand.
2) Secure : Java is more secure than C/C++ as does not allow developers to
create pointers, thus it becomes impossible to access a variable from outside if
it’s not been initialized.
3) Portable: Java code that is written on one machine can run on another
machine. The platform independent byte code can be carried to any platform
for execution that makes java code portable.
4) Object-oriented: Object oriented programming is a way of organizing
programs as collection of objects, each of which represents an instance of a
class
5) Robust: Robust means reliable. Java programming language is developed
in a way that puts a lot of emphasis on early checking for possible errors,
that’s why java compiler is able to detect errors that are not easy to detect in
other programming languages.
The main features of java that makes it robust are:
 Garbage collection , Exception Handling , Memory allocation.
6) Multithreaded: Multithreading is a Java feature that allows concurrent
execution of two or more parts of a program for maximum utilisation of CPU.

7) Architecture-neutral: Compiler converts the java file into byte-code and


this byte code is machine independent, java virtual machine can easily
translate this byte code into machine specific code. This makes java
architectural neutral programming language.
8) Interpreted: Java Programs are executed line by line.
9) High performance: Java is significantly faster than other traditional
interpreted programming languages. Compiled java code which is known as
byte code is like a machine code, that allows a faster execution. Java uses Just
in Time compiler which can execute the code on demand, this allows to
execute only the method that is being called, which makes it faster and
efficient.
10) Distributed: The java programs can be distributed on more than one
systems that are connected to each other using internet connection. Objects on
one JVM (java virtual machine) can execute procedures on a remote JVM.
11) Dynamic: Java is a dynamic programming language. OOPs allows
developers to add new classes to the existing packages, add new methods to
the existing classes as well as modifying the method without changing the
original method code by using the concept of method overriding.
1.4 OBJECT ORIENTED PROGRAMMING

1.4.1 Two Paradigms : Code and Data

Every Programs consists of two elements : Code and Data

Code and Data are the two paradigms that governs how programs are
constructed.
Programs can be conceptually organized around its code and data
means:
-- some programs are written around “what is happening” and others are
written around “who is being affected.”

The two approaches of coding are :


- process oriented model
- object oriented programming
- Process oriented model : In this approach the program is written in series
of linear steps (code). Disadvantage of this approach
is that as the program grows bigger and more the complex.

- 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.
1.5 PRINCIPLES OF OOPS

Following are the four principles of object oriented programming:


Abstraction
Encapsulation
Inheritance
Polymorphism

1.5.1 Abstraction: Abstraction is a process


which displays only the information
needed and hides the unnecessary
information. The main purpose of abstraction is data hiding. Abstraction
means selecting data from a large number of data to show the information
needed, which helps in reducing programming complexity and efforts.
PRINCIPLES OF OOPS
Example: When driving the car the driver needs to know only how to apply
the brake to stop the car, but need not know how the car stopped (breaks
works).
Example: When you visit an ATM you know only how to deposit or withdraw
or check the balance but, don’t know how it is working such as how machine
is dispensing amount, deposited into account and displaying balance

.
PRINCIPLES OF OOPS
1.5.2 Inheritance: Inheritance is a method in which one object
acquires/inherits another object’s properties, and inheritance also supports
hierarchical classification. The idea behind this is that we can create new
classes built on existing classes, i.e., when you inherit from an existing class,
we can reuse methods and fields of the parent class. Inheritance represents the
parent-child relationship.
Example: In real life a Child can inherits many things from parents like
colour, height, way of walking etc. but, the child also have its own properties
like education, playing etc.
PRINCIPLES OF OOPS
1.5.3 Encapsulation: Encapsulation is the process that binds together the data
and code into a single unit and keeps both from being safe from outside
interference and misuse.
Encapsulation is achieved by declaring the variables as private and providing
public setter and getter methods to modify and view the variable values.
PRINCIPLES OF OOPS
1.5.4 Polymorphism: Polymorphism refers to many forms, or it is a process
that performs a single action in different ways.
Example: a add() Method can be used to add two integers, add three float, add
two int and one float etc.
1.7 TWO CONTROL STATEMETS
if Statement and for loop : used to explain how to use block of code.

1.7.1 if statement: The syntax of if statement in java is syntactically is


identical to if statement in c and C++ lanaguage. The if statement in java
works similar to if in other languages. The simplest form of is is:
if( condition)
statement ;

condition is a Boolean expression. If condition is true, then the statement is


executed. If condition is false, then the statement is bypassed.
Example of if statement

class ifExample{
public static void main(String args[]) {
int age=10; // variable declared and initialized
if(age>=18)
System.out.println( “You are eligible to vote”);
}
}
Example of if statement

class ifExample{
public static void main(String args[ ]) {
int x=10; // variable declared and initialized
int y=20; // variable declared and initialized
if( x> y)
System.out.println( “X is greater than Y”);
if( x < y)
System.out.println( “X is Smaller than Y”);
if( x= = y)
System.out.println( “X is equal to Y”);
}
}
1.7.2 for loop
for loop: The syntax of for loop is:
for(initialization; condition; iteration)
statement ;

The initialization portion of the loop sets a loop control variable to an initial
value.
The condition is a Boolean expression that tests the loop control variable.
if the outcome of that test is true, the for loop continues to iterate. If it is
false, the loop terminates.
 The iteration expression determines how the loop control variable is
changed each time the loop iterates.
for loop
Example of for loop:
class ForTest
{
public static void main(String args[])
{
int x;
for(x = 0; x<10; x = x+1)
System.out.println("The value of x is : " + x);
}
}
Using Block of Code
In java we can group two or more statements in block of code, also called
code block.
The statements are written between the open curly bracket and close curly
bracket.
 We use code block when we need to execute multiple statement when
particular condition is evaluated to true.
Example:
if( x> y)
{
x=y;
y=0;
}
1.8 Using Block of Code
In java we can group two or more statements in block of code, also called
code block.
The statements are written between the open curly bracket and close curly
bracket.
 We use code block when we need to execute multiple statement when
particular condition is evaluated to true.
Example:
if( x> y)
{
x=y;
y=0;
}
1.9 LEXICAL ISSUES
1.19.1 Whitespace: Java is a free form language. This means that you do not
need to follow any special indentation rules. In java , white spaces is a
space , tab or new line.
1.19.2 Identifiers: Identifiers are used for class names , method names and
variable names.
Rules to define the identfiers
 Names can contain letters, digits, underscores, and dollar signs
 Names must begin with a letter
 Names should start with a lowercase letter and it cannot contain
whitespace
 Names can also begin with $ and _
 Names are case sensitive ("myVar" and "myvar" are different variables)
 Reserved words (like Java keywords, such as int or boolean) cannot be
used as names
1.19.3 Literals: A constant value that is assigned to a variable is called
Literals. Example: integer literal
int num =21; // 21 is an integer literal
1.19.4 Comments: Comments in Java are the statements that are not
executed by the compiler and interpreter.
comments can be used to provide information or explanation
about the variable, method, class or any statement.
There are 3 types of comment in java.
 single line comment that begins with double slash //
 multi line comment. That begins with /* and ends with */
 documentation comment This type of comments is used generally when
you are writing code for a project/ software package. It helps you to
generate a documentation page for reference, which can be used for
getting information about methods present, its parameters, etc.It begins
with a /** and ends with a*/.
1.19.5 Separators: There are few symbols in java that are used as
separators.The most commonly used separator in java is the semicolon ' ;
'. some other separators are Parentheses '( )' , Braces ' {} ' , Bracket ' []
' , Comma ' , ' , Period ' . ' .
1.10 KEYWORDS
Keywords are predefined which have a unique meaning and functionality
in Java programming language. These keywords are also known as
reserved keywords which mean they cannot be used as a variable name,
class, method or any other identifier. There are 57 reserved keywords in
Java.
1.11 Java Is a Strongly Typed Language
1.12 Primitive Data Types
Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean.
The size of the primitive data types does not change with changing the
operating system These can be put in four groups:
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.
1.12.1 Integer Data Types
byte: The byte data type is commonly used when we want to store very
small numbers of very limited size. For example, the index record of the
notebook.
The byte data type can have data value in the range of -128 to 127.
The byte data values require 1 bytes memory space in the computer’s
memory.
The default value of the byte is 0.
Synatx: byte variable_name = value;
Example: byte b =10;

Note: We should initialize the value to byte variable within -128 to 127. if
not compiler will give error.
short: The short data type is commonly used when we want to save
memory in large arrays. For example, we can use a short data type for storing
the admission number of the students of the school.
The short data type can have data value in the range of -32,768 to 32,767.
The short data values require 2 bytes memory space in the computer’s
memory.
The default value of the byte is 0.
Synatx: short variable_name = value;
Example: short s =128;

Note: We should initialize the value to short variable within -32,768 to


32,767. if not compiler will give error.
int: The int data type is commonly used when we want to save memory in
large arrays. For example, we can use a int data type for storing the admission
number of the students of the school.
The int data type can have data value in the range of -2^31 to 2^31-1.
The int data values require 4 bytes memory space in the computer’s
memory.
The default value of the byte is 0.
Synatx: int variable_name = value;
Example: int b =10;

Note: We should initialize the value to int variable within -


2,147,483,648 to 2,147,483,647. if not compiler will give error.
long: The long data type is used when the int data type cannot handle a
wider range than the int data type range.
The long data type can have data value in the range of -2^63 to 2^63-1.
The long data values require 8 bytes memory space in the computer’s
memory.
The default value of the byte is 0.
Synatx: long variable_name = value;
Example: long b =10;

Note: We should initialize the value to long variable within


-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. if not compiler
will give error.
1.13 Floating Data Types
Floating Data types are of two types float and double
float: This type of data types is used to store the decimal values.
This data type is used to store numbers that have decimals up to 6 and 7
points. For example 8.123456 this number can be stored in the float data
type.
The default value of the float data type is 0.0.
The float data values require 4 bytes memory space in the computer’s
memory.
The float data type can have data value in the range of 1.40239846e-45f to
3.40282347e+38f.
Syntax: float varaiable_name = value f;
Example: float sum = 12.56f
double: The double data type is most commonly used for storing large
decimal values for example the value of pi i.e 3.1473…
 The default value of the float data type is 0.0.
This data type is used to store numbers that have decimals up to 15 decimals
The double data values require 8 bytes memory space in the computer’s
memory.
The double data type can have data value in the range of
4.94065645841246544e-324 to 1.79769313486231570e+308
Syntax: double varaiable_name = value ;
Example: double sum = 12.5634567893222;
Example of Floating Data types:
1.14 Character Data Type
Character Data Type: The char data type is used to store a single
character/letter enclosed in the single parenthesis.
Syntax: char variable_ name= ‘data value’;
The character must be enclosed by single quotes.
The default value of the char is ‘\u0000’.
Memory allocation of the char data type is 2 bytes.
The Range of char datatype is the ASCII value is -128 to 127.
The char data type can have data value in the range of 0 (‘\0000’) to 65535
(‘\ffff’)
Example of Character Data type:
1.15 Boolean Data Type
Boolean Data Type: The boolean data type is used to store false or true
boolean values.
Syntax: boolean variable name = data value;
The boolean data type stores only two kinds of values i.e false or true.
The default value of the boolean data type is false.
Memory allocation of the double data type is 1 byte.
1.16 Literals
Literals in Java refers to a fixed value that is assigned to a variable .

Java supports integral literal, floating-point literal, character literal and


boolean literal, string literal and NULL literal.

1.16.1 Integral Literals : These types of literals are the sequence of digits. There
are four types of intergral literals.
Decimal
Octal.
Hexadecimal.
Binary
Decimal Integer: These are the set of numbers that consist of digits from 0 to 9.

It may have a positive (+) or negative (-) Note that between numbers commas and

non-digit characters are not permitted. For example, 5678, +657, -89, etc.

int decVal = 26;

Octal Integer: It is a combination of number have digits from 0 to 7 with a

leading 0. For example, 045, 026,

int octVal = 067;


Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as

hexadecimal integers. It may also include a character from a to f or A to F that

represents numbers from 10 to 15, respectively. For example, 0xd, 0xf,

int hexVal = 0x1a;

Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can

create binary literals in Java SE 7 and later). Prefix 0b represents the Binary

system. For example, 0b11010.

int binVal = 0b11010;


Example of Integral Literals:

Output:
1.16.2 Floating Point Literals:
The values that contain decimal are floating literals. In Java, float and double
primitive types fall into floating-point literals.
Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc.
It is a 32-bit float literal.
Floating-point literals for double type end with D or d. It is optional to write D or
d. For example, 6d, 8.354D, etc. It is a 64-bit double literal.
It can also be represented in the form of the exponent.
Floating: float length = 155.4f;
Decimal: double interest = 99658.445;
Decimal in Exponent form: double val= 1.234e2;
Example of Floating Point Literals:

Output:
1.16.3 Boolean Literals:
Boolean literals are the value that is either true or false. It may also have values 0
and 1. For example, true, 0, etc.
boolean isEven = true;
1.16.4 Null Literals:
Null literal is often used in programs as a marker to indicate that reference type
object is unavailable. The value null may be assigned to any variable, except
variables of primitive types.
String stuName = null;
Student age = null;
1.16.5 String Literals:
String literals are the value that is enclosed in double quotes. For
example, ”Welcome”.
String name = ”Ramesh”;
Example of boolean, null and String Literals:

Output:
1.17 VARIABLES
Variables:
Declaring a Variable
Dynamic Initialization
The Scope and Lifetime of Variables

Variable: Variables are the containers for storing the data.

1.17.1 Declaring a variable: Every variable should be declared before it is used


in the program.
Syntax: datatype variable_name;
Example: int weekDay;
Variable Initialization: Initializing the variable refers to assigning the value to

the variable

Syntax: datatype variable_name = value;


Example: int x=20;

1.17.2 Dynamic Initialization: When a variable is initialized using any valid


expression during declaration then it is called Dynamic initialization.
class DynInit {
public static void main(String args[ ]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Types of Variables :

Global Variable: Variables that are declared outside the class are called Global

variables.

Instance Variable: Variables that are defined inside the class but outside the

methods are called instance variables.

Local Variable: Variables that are declared insde the methods are called local

variables.
1.17.3 SCOPE AND LIFE TIME OF VARIABLES
In java we can define the variables in any block.
Block defines the scope.
Each block defines the new scope.
A scope determines that objects are visible to other parts of your program. It
also determines the lifetime of those objects.
 Variables declared inside a scope are not visible (that is, accessible) to
code that is defined outside that scope.
Therefore when we declare a variable within a scope, we are localizing that
variable and protecting it from unauthorized access and/or modification.
Example on Scope of the variable
Example on Scope of the variable
1.18 TYPE CONVERSION AND CASTING

 Type Conversion: The process of converting data of one type to another type

is called Type conversion.

 Example: byte b = 12;

int x = b;

The data type of 12 which was byte has been converted to int. but 12 will remain

same.

 In java it is possible for the programmer to convert data of one type to another.

If both the datat ypes are compatible then java perform automatic type

conversion.
1.18.1 Automatic Type Conversion :

Automatic Conversion is also known as Widening Conversion or implicit

Conversion .

Automatic Type conversion is the process of converting the data type with

lower values to data types with higher values without incurring any data loss.

Implicit type conversion is automatically done by the compiler. When both data

types are compatible. That is destination type is larger than source type
Type Casting :

Type casting is also known as Narrowing Conversion or Explicit

Conversion .

Type Casting is the process of converting the data type with higher values to

data types with lower values without incurring any data loss.

Syntax: to type cast explicitly

dataType variable = ( Target) Value;


1.18.2 TYPE PROMOTION RULES

All byte, short, and char values are promoted to int.


 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.

Example:
byte b= 20, c=12, m;
m = b*c; // here the result of expression b*c value is promoted to int.
Example: int x=10;
float y= 12.9f, d;
d = (x* 2)/y; // here the result of expression (x*2)/y is promoted to float
TYPE PROMOTION RULES

Example:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c; // result of a*b/c is converted to int

Example:
byte b = 10;
b = b * 2; // Error here the result of expression b*2 is promoted to
int by default , which cant be stored into b variable since
it is byte.
SUMMARIZE : TYPE CONVERSION AND CASTING

 Type Conversion:
1.19 ARRAYS

Array: Array is a collection of elements of similar data types. Array can be of


type int, float, char , double etc.

Arrays are classified as:


One dimensional Array
Two Dimensional Array
Multi Dimensional Array
1.19.1 One Dimensional Array: is a list of liked- typed variables. In
order to create an array one must first create an array variable of desired
type.
General Syntax to declare one dimensional array :
type var_name[ ];
Example of One Dimensional Array Declaration:
int month_days[ ] ;
int: specifies the data type
month_days: specifies the name of the array.
The above declaration represents an array with no values. That is month_days
is set to null. To link month_days with an actual, physical array of integers,
we must allocate one using new and assign it to month_days. new is a special
operator that allocates memory.
The general form of new as it applies to one-dimensional arrays appears
as follows:
array-var = new type[size];

Example:
month_days = new int[12]; // This example allocates
a 12-element array of integers and links them to month_days.
Once you have allocated an array, you can access a specific element in the array
by specifying its index within square brackets. All array indexes start at zero.

For example: the statement assigns the value 28 to the second element of
month_days.
month_days[1] = 28;

Below Statement prints displays the value stored at the index 3.


System.out.println(month_days[3]);
Example of One Dimensional Array:
Improvised Version of One Dimensional Array:
Program to find sum and average of array elements:
1.19.2 Multi Dimensional Array

Multi dimensional array are array of arrays. To declare a multidimensional array


variable, specify each additional index using another set of square brackets. For
example, the following declares a two dimensional array variable called twoD.
int twoD[ ] [ ] = new int [4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is


implemented as an array of arrays of int.

Conceptual view of two


dimensional Array
Example of two Dimensional Array

You might also like