0% found this document useful (0 votes)
6 views54 pages

Unit 1 Introduction To Java-1

The document provides an introduction to Java, detailing its history, features, and programming structure. It covers essential concepts such as object-oriented programming, platform independence, and the Java Runtime Environment (JRE) alongside the Java Virtual Machine (JVM). Additionally, it explains Java data types, constants, variables, and the syntax used in Java programming.

Uploaded by

Sahana Patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views54 pages

Unit 1 Introduction To Java-1

The document provides an introduction to Java, detailing its history, features, and programming structure. It covers essential concepts such as object-oriented programming, platform independence, and the Java Runtime Environment (JRE) alongside the Java Virtual Machine (JVM). Additionally, it explains Java data types, constants, variables, and the syntax used in Java programming.

Uploaded by

Sahana Patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Divya S R , Assistant Professor, Dept.

of Computer Application

Unit 1:
Introduction to java:
Java programming language was originally developed by Sun
Microsystems which was initiated by James Gosling and released in 1995 as
core component of Sun Microsystems. Java platform (Java 1.0 [J2SE]).

The latest release of the Java Standard Edition is Java SE 8. With the
advancement of Java and its widespread popularity, multiple configurations were
built to suit various types of platforms.
For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.

The new J2 versions were renamed as Java SE, Java EE, and Java ME
respectively. Java is guaranteed to be Write Once, Run Anywhere.

Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm based
on the concept of “objects”, which may contain data in the form of fields,
often known as attributes and code in the form of procedures, often known as
methods.

Platform independent:
Unlike many other programming languages including C and C++, when
Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.

Features of Java
1. Simple: Java is designed to be easy to learn. If you understand the basic
concept of OOP.
2. Secure:
 Java program cannot harm other system thus making it secure.
 Java provides a secure means of creating Internet applications.
 Java provides secure way to access web applications.

1
Divya S R , Assistant Professor, Dept. of Computer Application

3. Portable:
 Java programs can execute in any environment for which there is a
Java run-time system.
 Java programs can run on any platform (Linux, Window, Mac OS)
 Java programs can be transferred over world wide web (e.g: applets).
4. Object-oriented:
 Java programming is object-oriented programming language.
 Like C++, java provides most of the object oriented features.
 Java is pure OOP Language. (while C++ is semi object oriented)
5. Robust:
Java encourages error-free programming by being strictly typed and
performing run- time checks.
6. Multithreaded:
Java provides integrated support for multithreaded programming.
7. Interpreted :
 Java supports cross-platform code through the use of Java bytecode.
 Bytecode can be interpreted on any platform by JVM (Java Virtual
Machine).
8. High performance:
 Bytecodes are highly optimized.
 JVM can execute bytecodes much faster.
9. Distributed:
 Java is designed with the distributed environment.
 Java can be transmitted over internet.
10. Platform Independent

 A platform is the hardware or software environment in which a program


runs.
 Java code can be run on multiple platforms.

2
Divya S R , Assistant Professor, Dept. of Computer Application

Structure of Java Program

1. Documentation Section
The documentation section is an important section but optional for a Java
program. It includes basic information about a Java program. The information
includes the author's name, date of creation, version, program name,
company name, and description of the program. It improves the readability
of the program
Ex: //First Java Program

2. Package Declaration
The package declaration is optional. It is placed just after the documentation
section. In this section, we declare the package name in which the class is
placed. Note that there can be only one package statement in a Java program.
It must be defined before any class and interface declaration.
Example: package javatpoint; //where javatpoint is the package name

3. Import Statements
import keyword is used to import built-in and user-defined packages into java
source file. So that the class can refer to a class that is in another package by
directly using its name.
The keyword is import. The general syntax is
import package1 [.package2].[classname].*;

3
Divya S R , Assistant Professor, Dept. of Computer Application

Example
import [Link]; //it imports the Scanner class only
import [Link].*; //it imports all the class of the [Link] package

4. Interface Section
It is an optional section. We can create an interface in this section if required.
We use the interface keyword to create an interface. An interface is a slightly
different from the class. It contains only constants and method declarations.
Example:

interface car

void start();

void stop();

}
5. Class Definition
In this section, we define the class Without the class, we cannot create any Java
program. A Java program may conation more than one class definition. We use
the class keyword to define the class. It contains information about user-defined
methods, variables, and constants. Every Java program has at least one class
that contains the main() method. For
Example:
class Student //class definition
{
}

6. Main Method Class

In this section, we define the main() method. It is essential for all Java
programs. Because the execution of all Java programs starts from the main()
method. In other words, it is an entry point of the class. It must be inside the
class. Inside the main method, we create objects and call the methods.

Example:
public static void main(String args[])
{
}

4
Divya S R , Assistant Professor, Dept. of Computer Application

Example:

Java Runtime environment (JRE)


The Java Runtime Environment (JRE) is a set of software tools for
development of Java applications. It combines the Java Virtual Machine (JVM),
platform core classes and supporting libraries. JRE is part of the Java
Development Kit (JDK), but can be downloaded separately. JRE was originally
developed by Sun Microsystems Inc.

Java virtual machine (JVM)


The JVM is a program that provides the runtime environment necessary
for Java programs to execute. Java programs cannot run without JVM for the
appropriate hardware and OS platform.
Java programs are started by a command line. This brings up the JVM as
an operating system process that provides the Java runtime environment. Then
the program is executed in the context of an empty virtual machine. When the
JVM takes in a Java program for execution, the program is not provided as Java
language source code. Instead, the Java language source must have been
converted (or compiled) into a form known as Java bytecode.
Java bytecode must be supplied to the JVM in a format called class files.
These class files always have a .class extension.
The JVM is an interpreter for the bytecode form of the program. It steps

5
Divya S R , Assistant Professor, Dept. of Computer Application

through one bytecode instruction at a time. It is an abstract computing machine


that enables a computer to run a Java program.

Graphical representation

10100011
11111011
1

Bytecode:
Bytecode is the intermediate representation of a Java program, allowing
a JVM to translate a program into machine-level assembly instructions.
When a Java program is compiled, bytecode is generated in the form of a(
.class) file. This (.class) file contains non-runnable instructions and relies on a
JVM to be interpreted.

6
Divya S R , Assistant Professor, Dept. of Computer Application

Java comments
The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation
about the variable, method, class or any statement. It can also be used to hide
program code for specific time.
A single-line comment begins with a // and ends at the end of the line.

Syntax example
//Comment
//This is single line comment

Java tokens
Each individual characters or units used in a java program are termed as
tokens. Java program are written using these tokens and the syntax of the
language. The java has various types of tokens as follows as
 Identifier
 Keywords
 Separators
 Punctuators
 Constants
 Variables
 Operators

Java Identifiers:
All Java components require names. Names used for classes, variables and
methods are called identifiers. In Java, there are several points to remember
about identifiers.
They are as follows:
All identifiers should begin with a letter (A to Z or a to z), or an underscore (_).
After the first character, identifiers can have any combination of characters. A
keyword cannot be used as an identifier.
“Most importantly identifiers are case sensitive”.

7
Divya S R , Assistant Professor, Dept. of Computer Application

Rules for identifiers


 First letter must be an alphabet followed by letters or digits.
 Special characters are not allowed except underscore( _ ) sign.
 It cannot be keywords.
 They can be of any length
 Uppercase and lowercase letters are distint.

Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using
modifiers.
There are two categories of modifiers:

Access Modifiers:
default, public, protected, private

Non-access Modifiers:
final, abstract

Keywords

8
Divya S R , Assistant Professor, Dept. of Computer Application

Constants
Any fixed value that does not change during the execution of a program is
known as constant.
The general syntax is

final datatype identifier_name=value;

Example: final int PI=3.14;


where final is a keyword, int is a datatype, PI is variable name, 3.14 is value.

a) Integer constant
The numbers which represents without decimal part is known as integer
constants.
There are three types of constants
 Decimal integer constants
 Octal integer constants
 Hexadecimal integer constants
Decimal integer constants
It is a combination of digits from 0 through 9, preceded by an optional
minus signs. The following table shows some valid and in-valid example.
Valid In-valid
-125 +250 500 1,500 20.22 20*10

9
Divya S R , Assistant Professor, Dept. of Computer Application

Octal integer constants


It is a combination of digits from 0 through 7, preceded by an optional
minus signs. The following table shows some valid and in-valid example
Valid In-valid
025 030 035 575 0580 04.4

Hexadecimal integer constants


It is a combination of digits from 0 through 9 and alphabets from A
through F. The following table shows some valid and in-valid example
Valid In-valid
0x5 0A10 0B91 05.5 0A.8 0AB.90

b) Real constants
A Real Constant must have at Least one Digit.
• it must have a Decimal value.
• it could be either positive or Negative.
• if no sign is Specified then it should be treated as Positive.
• No Spaces and Commas are allowed in Name.
Like 251, 234.890 etc are Real Constants.
In The Exponential Form of Representation the Real Constant is Represented in
the two [Link] part before appearing e is called mantissa where as the part
appearing after e is called Exponent.

0.65 e 4
Mantissa Exponent

Example: 0.65e4

c) Single Character Constants


A Character is Single Alphabet a single digit or a Single Symbol that is enclosed
within Single inverted commas.
Like ‘S’ ,’1’ etc are Single Character Constant.

10
Divya S R , Assistant Professor, Dept. of Computer Application

d) String Constants: String is a Sequence of Characters Enclosed between


double Quotes These Characters may be digits ,Alphabets Like “Hello” , “1234”
etc.

e) Boolean constants:
It is a special type of constant represents as true or false.
Valid In-valid
true false “True” TRUE FALSE

Backslash Character Constants


Java also supports backslash character constants. These are used in output
methods. It is also known as escape sequence.
For Example, \n, \t, \a, etc.

11
Divya S R , Assistant Professor, Dept. of Computer Application

Data types
In Java, each type of data (such as integer, character, etc. ) is predefined as
part of the programming language and all constants or variables defined within a
given program must be described with one of the data types.
Data types represent the different values to be stored in the variable. In java,
there are two categories of data types:
a) Primitive data types
b) Non-primitive data types

Primitive types
Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean. The primitive types are also commonly referred to as
simple types and they are grouped into the following four groups:

1) Integers - This group includes byte, short, int, and long. All of these are
signed, positive and negative values. The width and ranges of these
integer types vary widely, as shown in the following table:

12
Divya S R , Assistant Professor, Dept. of Computer Application

2) Floating-point numbers– They are also known as real numbers. This


group includes float and double, which represent single and double
precision numbers, respectively. The width and ranges of them are shown
in the following table:

3) Characters- This group includes char, which represents symbols in a


character set, like letters and numbers. char is a 16-bit type. The range of
a char is 0 to 65,536. There are no negative chars.

4) Boolean - This group includes boolean. It can have only one of two
possible values, true or false.

Non-Primitive data types


There are five types of non-primitive data types in Java. They are as follows:
1. Class
2. Object
3. String
4. Array
5. Interface

Class
A class in Java is a user defined data type i.e. it is created by the user. It
acts a template to the data which consists of member variables and
methods.

Objects
An object is the variable of the class, which can access the elements of
class i.e. methods and variables.

13
Divya S R , Assistant Professor, Dept. of Computer Application

Interface:
An interface is similar to a class however the only difference is that its methods
are abstract by default i.e. they do not have body. An interface has only the final
variables and method declarations. It is also called a fully abstract class.

String:
A string represents a sequence of characters for example "Javatpoint", "Hello
world", etc. String is the class of Java.
One of the ways to create a string and store a value in it is shown below:
Example: String str = "You're the best";

Array:
An array is a data type which can store multiple homogenous variables i.e.,
variables of same type in a sequence. They are stored in an indexed manner
starting with index 0. The variables can be either primitive or non-primitive data
types.
The general format is
data_type int:
Example: int [ ] marks;

Variables
A variable is the holder that can hold the value while the java program is
executed. A variable is assigned with a data type. It is name of reserved area
allocated in memory. In other words, it is a name of memory location. There are
three types of variables in java: local, instance and static.

The general syntax of variable declaration

Datatype variable=value;

Example
int a, b, c; // Declaration of variables a, b, and c.
int a = 20, b = 30; // initialization
byte B = 22; // Declaration initializes a byte type variable B.

14
Divya S R , Assistant Professor, Dept. of Computer Application

Variables are containers for storing data values.


In Java, there are different types of variables, for example:
 Integer variable
 Float variable
 Double variables
 Character variables
 String variables

 String variable - stores text, such as "Hello". String values are


surrounded by double quotes
The general syntax is
data_type var1, var2,…… varn;
Example: String s1,s2;

 Integer variable- stores integers (whole numbers), without decimals,


such as 123 or -123
The general syntax is
data_type var1, var2,…… varn;
Example: int a,b;

 Double variable- A number with more fraction is called double floating


point.
The general syntax is
data_type var1, var2,…… varn;
Example: double a,b;

 Float variable - stores floating point numbers, with decimals, such as


19.99 or -19.99
The general syntax is
data_type var1, var2,…… varn;
Example: float a,b;

15
Divya S R , Assistant Professor, Dept. of Computer Application

 Character variable - stores single characters, such as 'a' or 'B'. Char


values are surrounded by single quotes
The general syntax is
data_type var1, var2,…… varn;
Example: char a,b;

Initializing variable
When a variable gets initialized during declaration is termed as static
initialization. Under this situation a variable is assigned directly with assignment
operator.
There are of two types of initialization
1. Static initialization
2. Dynamic initialization
1. Static initialization
When a variable gets initialized during declaration is termed as static
initialization. Under this situation a variable is assigned directly with
assignment operator.
Example:
Data Type Declaration Static Initialization
int int x; x=10;
float float y; y=5.5f;
double double z; z=25;
char char ch ch=’A’

2. Dynamic Initialization
When a variable gets initialized runtime is termed as dynamic
initialization. Under this situation, a variable is assigned with the outcome
of any arithmetic or logical operations.
Example:
Data Type Declaration Static Initialization
int int x,y,z; x=x+y;
float float a,b,c; c=a+b;
double double z; z=25+10;
char char ch ch=”computer”.charAt(0);

16
Divya S R , Assistant Professor, Dept. of Computer Application

Giving values to variables


A variable must be given a value after it has been declared, but before it is used
in an expression. This can be achieved in 3 ways:
 By using an Assignment statement
 By using a Stream Reader
 By using Command Line argument

By using an assignment statement


The simple method of giving value to a variable is through the assignment
statement as follows.
Syntax is
Variable_name = value;

Example: a = 10;
a = b;

By using a Stream Reader


This is a user’s friendly statement where you can accept the value from
the console at the time of execution of the program. In order to develop a
program using streams, some of the functions related with input/output
operations are invoked.
Some of the InputStream is
 Declaring a java library package at the beginning of the program.
It allows performing all types of input and output tasks during the
execution of the program.
The general format is:
import [Link].*;
 Declaring buffer to store the data values at the time of execution along
with the IOException with the main().
The format is
InputStreamReader read = InputStreamReader([Link])
BufferedReader in = BufferedReader(read);

17
Divya S R , Assistant Professor, Dept. of Computer Application

By using Command Line argument


Command line arguments are parameters that are supplied to the application
program at the time of invoking it for execution.
The following program shows the usage of command line arguments where,
“args[]” is an array of strings used to collect command line arguments.
Example:
class commandline
{
public static void main(String args[])
{
[Link]("Your first argument is: "+args[0]);
}
}
compile by > java [Link]
run by > java commandline BCA

Output: Your first argument is: BCA

Scope of Variables
1) Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
Example
class First
{
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable

// This variable is local to this main method only


[Link]("Local Variable: " + var);
}
}

18
Divya S R , Assistant Professor, Dept. of Computer Application

2) Instance Variable
A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static
It is called an instance variable because its value is instance-specific and is not
shared among instances.
Example
class GFG
{
public String geek; // Declared Instance Variable

public GFG() // Default Constructor


{

[Link] = "Shubham Jain"; // initializing Instance Variable


}
//Main Method
public static void main(String[] args)
{

// Object Creation
GFG name = new GFG();

// Displaying O/P
[Link]("Geek name is: " + [Link]);
}
}

3) Static variable
A variable that is declared as static is called a static variable. It cannot be local.
You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only once
when the class is loaded in the memory.
Example
class GFG
{
public static String geek = "Shubham Jain"; //Declared static variabl
public static void main (String[] args)
{
//geek variable can be accessed without object creation
[Link]("Geek Name is : "+[Link]);
}
}

19
Divya S R , Assistant Professor, Dept. of Computer Application

Differences between the Instance variables and the Static variables

Instance variable Static variable

Each object will have its own copy of Whereas we can only have one copy
an instance variable. of a static variable per class,
irrespective of how many objects we
create.

Changes made in an instance In the case of a static variable,


variable using one object will not be changes will be reflected in other
reflected in other objects as each objects as static variables are
object has its own copy of the common to all objects of a class.
instance variable
We can access instance variables static variables can be accessed
through object references directly using the class name.

Syntax: Static and instance variables


class GFG
{
// Static variable
static int a;

// Instance variable
int b;
}

Implementing a java program


Implementation of a java application program involves a series of steps. They
include:
 Creating the program
 Compiling the program
 Running the program

20
Divya S R , Assistant Professor, Dept. of Computer Application

Creating the program


We can create a program using any text editor. Assume that we have entered
the following program:
class firstprogram
{
public static void main(String[] args)
{
[Link]("Computer Application");
}
}
We must save this program in a file called [Link] ensuring that the
file name contains the class name properly. This file is called the source file.
Note that all Java source files will have the extension java.

Compiling the program


To compile the program, we must run the Java Compiler javac, with the name
of the source file on the command line as shown below:
If everything is OK, the javac compiler creates a file called [Link]
containing the bytecodes of the program. Note that the compiler automatically
names the bytecode file as <classname>.class.

Syntax: to compile:- javac [Link]


Example: javac [Link]

21
Divya S R , Assistant Professor, Dept. of Computer Application

Running the program


To run the program, we must run the Java interpreter java, with the name of
the class file on the command line.

To run we have to use


java [Link]
Example:
java [Link]

Operators
Operators in Java can be classified into 6 types:
 Arithmetic Operators.
 Assignment Operators.
 Relational Operators.
 Logical Operators.
 Unary Operators.
 Bitwise Operators

22
Divya S R , Assistant Professor, Dept. of Computer Application

1. Arithmetic Operators in Java


Arithmetic Operators are used to perform mathematical operations like addition,
subtraction, etc. Assume that A = 10 and B = 20 for the below table.

Operator Description Example

(+) Addition Adds values on either side A+B=30


of the operator

Subtracts the right-hand


(–) Subtraction operator with left-hand A-B=-10
operator

(*) Multiplication Multiplies values on either A*B=200


side of the operator

(/) Division Divides left hand operand A/B=0


with right hand operator
Divides left hand operand
(%) Modulus by right hand operand and A%B=0
returns remainder

2. Assignment Operators in Java


An Assignment Operator is an operator used to assign a new value to a variable.
Assume A = 10 and B = 20 for the below table.

Operator Description Example

Assigns values from right side operands to left side


= c=a+b
operand

23
Divya S R , Assistant Professor, Dept. of Computer Application

3. Relational Operators in Java


These operators compare the values on either side of them and decide the
relation among them. Assume A = 10 and B = 20.

Operator Description Example

If the values of two


== operands are equal, then (A == B) is not true
the condition becomes
true.
If the values of two
!= operands are not equal, (A != B) is true
then condition becomes
true.
If the value of the left
operand is greater than
> the value of right (a > b) is not true
operand, then condition
becomes true.
If the value of the left
operand is less than the
< value of right operand, (a < b) is true
then condition becomes
true.
If the value of the left
operand is greater than or
>= equal to the value of the (a >= b) is not true
right operand, then
condition becomes true.
If the value of the left
operand is less than or
<= equal to the value of right (a <= b) is true
operand, then condition
becomes true.

4. Logical Operators in Java


The following are the Logical operators present in Java:

Operator Description Example

&& (and) True if both the operands is true a<10 && a<20

|| (or) True if either of the operands is true a<10 || a<20

True if an operand is false (complements the


! (not) !(x<10 && a<20)
operand)

24
Divya S R , Assistant Professor, Dept. of Computer Application

5. Unary Operator in Java

Unary operators are the one that needs a single operand and are used to
increment a value, decrement or negate a value.

Operator Description Example

increments the value by 1. There is post-increment


++ a++ and ++a
and pre-increment operators

decrements the value by 1. There is post decrement


-- a- - or - -a
and pre decrement operators

6. Bitwise Operator in Java


Bitwise operations directly manipulate bits. In all computers, numbers are
represented with bits, a series of zeros and ones. In fact, pretty much everything
in a computer is represented by bits. Assume that A = 10 and B = 20 for the below
table.

Operator Description Example

& (AND) returns bit by bit AND of input a&b

| (OR) returns OR of input values a|b

^ (XOR) returns XOR of input values a^b

~
returns the one’s complement. (all bits reversed) ~a
(Complement)

7. Ternary Operators in Java


The ternary operator is a conditional operator that decreases the length of code
while performing comparisons and conditionals. This method is an alternative
for using if-else and nested if-else statements. The order of execution for this
operator is from left to right.
Syntax:
(Condition1) ? (Statement1) : (Statement2);

25
Divya S R , Assistant Professor, Dept. of Computer Application

 Condition1: It is the expression to be evaluated which returns a boolean


value.
 Statement 1: It is the statement to be executed if the condition results in
a true state.
 Statement 2: It is the statement to be executed if the condition results in
a false state.

Control Structures
Java Control statements control the flow of execution in a java program, based
on data values and conditional logic used.
There are two main categories of control flow statements;
Selection statements:
a) if statement
b) if-else statement
c) Switch statement.
Loop statements:
a) while loop

b) do-while loop

c) for loop.

Selection statements:
The selection statements checks the condition only once for the program
execution.

a) If Statement:
The if statement executes a block of code only if the specified
expression is true. If the value is false, then the if block is skipped and
execution continues with the rest of the program.
The simple if statement has the following syntax

if (Condition)
{
statement(s);
}

26
Divya S R , Assistant Professor, Dept. of Computer Application

Example
public class programif
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
[Link](“a > b”);
if (a < b)
[Link](“b < a”);
}
}
b) If-else Statement
The if-else statement is an extension of the if statement. If the condition in
the if statement fails, the statements in the else block are executed.

The if-else statement has the following syntax:


if (booleanExpression)
{
statement1;
}
else
{
statement2;
}

Example:
public class ProgramIfElse
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
{
[Link](“a > b”);

27
Divya S R , Assistant Professor, Dept. of Computer Application

}
else
{
[Link](“b < a”);
}
}
}

c) Switch statement
The Java switch statement executes one statement from multiple
conditions. It is like if-else-if ladder statement.
 The case value must be of switch expression type only. The case value
must be literal or constant. It doesn't allow variables.
 The case values must be unique. In case of duplicate value, it renders
compile-time error.
 Each case statement can have a break statement which is optional. When
control reaches to the break statement, it jumps the control after the
switch expression. If a break statement is not found, it executes the next
case.
 The case value can have a default label which is optional.

The general Syntax is


switch(expression)
{
case value1:
statement
break;
case value2:
//code to be executed;
break;
.......
……….
default:
code to be executed if all cases are not matched;
}

28
Divya S R , Assistant Professor, Dept. of Computer Application

Example
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: [Link]("10");
break;
case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
//Default case statement
default:
[Link]("Not in 10, 20 or 30");
}
}
}

Break and Continue Statement

The break and continue statements are the jump statements that are used to skip
some statements inside the loop or terminate the loop immediately without
checking the test expression. These statements can be used inside any loops such
as for, while, do-while loop.

Break: It is used to exit from a switch statement or a loop. However break


statement cannot exit from nested loops, since it can exit only from the loop
containing it.

Syntax :

break;

29
Divya S R , Assistant Professor, Dept. of Computer Application

Example:

Class examplebreak
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
[Link](i);
if(i==5)
break;
}
}
}

Output:
1
2
3
4
5

Continue: It is used to skip the rest of the statements in the body of the loop and
execution continuous until the condition is satisfied.

Syntax:
continue;

Example:

Class examplebreak
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
[Link](i);
if(i==5)
continue;
}
}
}

30
Divya S R , Assistant Professor, Dept. of Computer Application

Output:
1
2
3
4
5
6
7
8
9
10

Difference between break and continue statement

Break continue

 It is used to transfer  It cannot be used in


control outside a switch switch statement
statement
 It is used to exit from a  It is used to skip the rest
loop of the statements of loop
body
 Only break cannot exit  In nested loops continue
from nested loops. cannot proceed to the
next iteration of the outer
loop.
 The general form is break  The general form is
continue.

d) Nested if statement
A nested if statement is an if statement placed inside another if statement.
Nested if statements are often used when you must test a combination of
conditions before deciding on the proper action.

The general syntax is

if(Condition1)
{
// Executes when the condition 1 is true

if(Condition2)
{
// Executes when the Boolean expression 2 is true
}
}

31
Divya S R , Assistant Professor, Dept. of Computer Application

Example:
public class Test
{

public static void main(String args[])

{
int x = 30;
int y = 10;

if( x == 30 )

if( y == 10 )

[Link]("X = 30 and Y = 10");


}
}

Looping Structures
Looping in programming languages is a feature which facilitates the execution of
a set of instructions/functions repeatedly while some condition evaluates to true.

a) while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
 While loop starts with the checking of condition. If it evaluated to true,
then the loop body statements are executed otherwise first statement
following the loop is executed. For this reason it is also called Entry
control loop
 Once the condition is evaluated to true, the statements in the loop body
are executed. Normally the statements contain an update value for the
variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks the
end of its life cycle.

32
Divya S R , Assistant Professor, Dept. of Computer Application

Syntax :
while (condition)
{
loop statements...
}

Example:
public class ProgramWhile
{
public static void main(String[] args)
{
int count = 1;
[Link](“Printing Numbers from 1 to 10”);
while (count <= 10)
{
[Link](count++);
}
}
}
}
b) DO-While loop
The do-while loop is similar to the while loop, except that the test condition is
performed at the end of the loop instead of at the beginning. The do—while loop
executes at least once without checking the condition. It begins with the
keyword do, followed by the statements that making up the body of the loop.
Finally, the keyword while and the test expression completes the do-while loop.
When the loop condition becomes false, the loop is terminated and execution
continues with the statement immediately following the loop.

The general Syntax is

do
{
statements..
}
while (condition);

33
Divya S R , Assistant Professor, Dept. of Computer Application

Example
public class dowhileloop
{
public static void main(String[] args)
{
int count = 1;
[Link](“Printing Numbers from 1 to 10”);
Do
{
[Link](count++);
}
while (count <= 10);
}
}

C) For loop
For loop provides a concise way of writing the loop structure. Unlike a while loop,
a for statement consumes the initialization, condition and increment/decrement
in one line thereby providing a shorter, easy to debug structure of looping.

The general Syntax is


for (initialization; testing condition; increment/decrement)
{
statement(s)
}

Example
public class ProgramFor
{
public static void main(String[] args)
{
[Link](“Printing Numbers from 1 to 10”);
for (int count = 1; count <= 10; count++)
{
[Link](count);
}

34
Divya S R , Assistant Professor, Dept. of Computer Application

}
}

Java Method
A method in Java or Java Method is a collection of statements that perform
some specific task and return the result to the caller. Methods in Java allow us to
reuse the code without retyping the code.

Types of Methods
There are two types of methods

1. Predefined Method: In Java, predefined methods are the method that is


already defined in the Java class libraries is known as predefined methods. It is
also known as the standard library method or built-in method. We can
directly use these methods just by calling them in the program at any point.
Example: Exponential, logarithm, square root, and trigonometric functions.

2. User-defined Method: The method written by the user or programmer is


known as a user-defined method. These methods are modified according to the
requirement.

In general, method declarations has six components :


1. Modifier: It defines the access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 types of access specifiers.
 public: It is accessible in all classes in your application.
 protected: It is accessible within the class in which it is defined and in its
subclass/es
 private: It is accessible only within the class in which it is defined.
 default: It is declared/defined without using any modifier. It is accessible
within the same class and package within which its class is defined.
2. The return type: The data type of the value returned by the method or void
if does not return a value.
3. Method Name: the rules for field names apply to method names as well, but
the convention is a little different.

35
Divya S R , Assistant Professor, Dept. of Computer Application

4. Parameter list: Comma-separated list of the input parameters is defined,


preceded with their data type, within the enclosed parenthesis. If there are no
parameters, you must use empty parentheses ().
5. Method body: it is enclosed between braces. The code you need to be
executed to perform your intended operations.

Example 2:
Inside main, call the myMethod() method:
public class Main
{
static void myMethod()
{
[Link]("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}
}

Output: "I just got executed!"

36
Divya S R , Assistant Professor, Dept. of Computer Application

Method Overloading
If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be
any number of arguments, if you write the method such as “adder(int,int)” for
two parameters, and “bca(int,int,int)” for three parameters then it may be
difficult for you as well as other programmers to understand the behaviour of the
method because its name differs.
So, we perform method overloading to figure out the program quickly.
Example:
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
[Link]([Link](2,3));
[Link]([Link](3,4,5));
}
}
Output:
5
12

37
Divya S R , Assistant Professor, Dept. of Computer Application

Math Class
The Java Math class has many methods that allows you to perform mathematical
tasks on numbers.

[Link];

[Link](x,y)

The [Link](x,y) method can be used to find the highest value of x and y:

Example:

[Link];
public class Main

public static void main(String[] args)

[Link]([Link](5, 10));

Output: 10

[Link](x,y)

The [Link](x,y) method can be used to find the lowest value of x and y:

Example:
[Link];
public class Main

public static void main(String[] args)

[Link]([Link](5, 10));

Output: 5

38
Divya S R , Assistant Professor, Dept. of Computer Application

[Link](x)

The [Link](x) method returns the square root of x:

Example:
public class Main
{
public static void main(String[] args)
{
[Link]([Link](64));
}
}
Output: 8

[Link](x)

The [Link](x) method returns the absolute (positive) value of x:

Example:
public class Main
{
public static void main(String[] args)
{
[Link]([Link](-4.7));
}
}
Output: 4.7

Floor() :
[Link]()
method returns the floor value of an argument i.e. the closest integer value
which is either less or equal to the passed argument.
Example:
class Main
{
public static void main(String[] args)
{

39
Divya S R , Assistant Professor, Dept. of Computer Application

double a = 3.8;
[Link]([Link](a));

}
}

Output: 3.0

Pow()
The pow() method returns the result of the first argument raised to the power of
the second argument.
Example:

class Main
{
public static void main(String[] args)
{

// computes 5 raised to the power 3


[Link]([Link](5, 3));

}
}

Output: 125.0

ceil()
The ceil() method rounds the specified double value upward and returns it. The
rounded value will be equal to the mathematical integer. That is, the value 3.24
will be rounded to 4.0 which is equal to integer 4.

Example:
class Main
{
public static void main(String[] args)
{

double a = 3.24;
[Link]([Link](a));

}
}

Output: 4.0

40
Divya S R , Assistant Professor, Dept. of Computer Application

round()
The round() method rounds the specified value to the closest int or long value
and returns it. That is, 3.87 is rounded to 4 and 3.24 is rounded to 3.

Example:
class Main
{
public static void main(String[] args)
{
double a = 3.87;
[Link]([Link](a));
}
}

Output: 4

41
Divya S R , Assistant Professor, Dept. of Computer Application

Arrays
Normally, an array is a collection of similar type of elements which has
contiguous memory location.

Java array is an object which contains elements of a similar data type.


Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.

The general syntax of an array is

datatype arrayName [arraySize];

Example: int num[5];

Adding Elements to Arrays


There are a number of ways to add elements to an array. This could be done by
initializing one element at a time or doing it all together in a single statement.
Some examples using the array called arrayInteger are shown here:

Example:
int arrayInteger[3] = {10,20,30};

This creates an array of size 3 with the name arrayInteger and initializes
arrayInteger[0] as 10, arrayInteger[1] as 20, arrayInteger[2] as 30.

The size of the array has to be specified inside the square brackets [] and the
elements have to be assigned inside the { }, separated by commas.

42
Divya S R , Assistant Professor, Dept. of Computer Application

Example:
int arrayInteger[] = {10,20,30,40};

Types of array
There are two types of an array
a) one Dimentional array
b) Two DImentional array

a) One Dimentional array: The group of logically related data items of same
data type which share a common name it contain one subscript.

Creation of one dimensional arrays


The creation of an array may involve three steps:
a)) Declaring the array
b)) Creating memory locations
c)) Putting values into the memory locations.

a)) Declaring the array:- Arrays in java may be declared in two forms:

Type1:
The general syntax is
Datatype arrayname[size];

Example:
int a[10];

Type2:
The general syntax is
Datatype[size] arrayname;

Example:
int[10] a;

43
Divya S R , Assistant Professor, Dept. of Computer Application

Example:

Output: one dimentional array elements are:

10

20

30

b)) Creating a memory locations


After declaring an array, we need to create it in the memory . java allows us to
create arrays using new operator.
The general form of one-Dimentional array is
data_type arrayname[ ];
arrayname = new data_type[size];
 data_type: declares the type of elements to be stored in the array such
as int, float, char or double.
 arrayname: is the name of the array which follows the rules of
constructing an identifier name.
 size: specifies the maximum number of elements that can be stored in
the array.

44
Divya S R , Assistant Professor, Dept. of Computer Application

The combined form can be represented as

data_type arrayname[ ] = new data_type[size];

Example:
int a[ ] = new a[5];
5 memory locations are reserved

CC)) Putting values into the memory locations (initialising values of 1D


array)
The elements of an array can be initialized in the declaration itself. The general
form of initialisation is:

data_type arrayname[ ] = { list of values};

 data_type: declares the type of elements to be stored in the array such


as int, float, char or double.
 arrayname: is the name of the array which follows the rules of
constructing an identifier name.
 The list of values of the array elements separated by commas.

Example:
int a[ ] = {10,20,30,40,50};
the array “a” reserve 5 storage locations

Array length
In java, all arrays store the allocated size ina variable named length. We can
obtain the length of the array using length.
int a[ ] = {10,20,30,40,50};
int n= [Link]; //the value of n is 5

45
Divya S R , Assistant Professor, Dept. of Computer Application

Example:
class arraylengthexample
{
public static void main(String[] args)
{
int[] num = new int[10];
int arraylength=[Link];
[Link]("The length of the array is: "+ arraylength);
}
}

Output:

The length of the array is: 10

b) Two Dimentional array: The group of logically related data items of same
data type which share a common name it contain two subscript.

The general syntax is


Datatype arrayname[row][column];

Creation of two dimensional arrays


The creation of an array may involve three steps:
a)) Declaring the array
b)) Creating memory locations
c)) Putting values into the memory locations.

46
Divya S R , Assistant Professor, Dept. of Computer Application

a)) Declaring the array:- Arrays in java may be declared in two forms:

Type1:
The general syntax is
Datatype arrayname[row][column];

Example:
int arrayname[3][3];

Type2:
The general syntax is
Datatype[row][column] arrayname;

Example:
int[4][4] arrayname;

b)) Creating a memory locations


After declaring an array, we need to create it in the memory . java allows us to
create arrays using new operator.
The general form of one-Dimentional array is

data_type arrayname[row][column];
arrayname = new data_type[row][column];

 data_type: declares the type of elements to be stored in the array such


as int, float, char or double.
 arrayname: is the name of the array which follows the rules of
constructing an identifier name.
 size: specifies the maximum number of elements that can be stored in
the array.
The combined form can be represented as

data_type arrayname[ ][ ]= new data_type[row][column];

Example:
int a[ ][ ] = new a[3][3];

47
Divya S R , Assistant Professor, Dept. of Computer Application

9 memory locations are reserved

CC)) Putting values into the memory locations (initialising values of 1D


array)
The elements of an array can be initialized in the declaration itself. The general
form of initialisation is:

data_type arrayname[ ][ ]= { list of values};

 data_type: declares the type of elements to be stored in the array such


as int, float, char or double.
 arrayname: is the name of the array which follows the rules of
constructing an identifier name.
 The list of values of the array elements separated by commas.

Example:
int arrayname[3][3] = {10,20,30,40,50,60,70,80,90};
the array “a” reserve 5 storage locations

48
Divya S R , Assistant Professor, Dept. of Computer Application

Example:

class twod
{
public static void main(String[] args)
{

int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++)


{
for (int j = 0; j < 2; j++)
{
[Link](arr[i][j] + " ");
}
[Link]();
}
}
}
Output:
1 2
3 4

Variable size arrays(Ragged arrays)

Variable sized arrays are data structures whose length is determined at


runtime rather than compile time. These arrays are useful in simplifying
numerical algorithm programming.
Or

A jagged array is an array of arrays such that member arrays can be of different
sizes, i.e., we can create a 2-D array but with a variable number of columns in
each row. These types of arrays are also known as Jagged arrays.

49
Divya S R , Assistant Professor, Dept. of Computer Application

Pictorial representation of Jagged array in Memory:

Create & Initialize Jagged Array


While creating an array of arrays you only specify the first dimension that
represents a number of rows in the array.

You can create a two-dimensional jagged array as follows:


int myarray[][] = new int[3][];
In the above declaration, a two-dimensional array is declared with three rows.

Once the array is declared, you can define it as a Jagged array as shown
below:
myarray[1] = new int[2];
myarray[2] = new int[3];
myarray[3] = new int[4];

 The first statement above indicates that the first row in the 2D array will
have 2 columns.
 The second row will have 3 columns while the
 third row will have 4 columns thereby making it a Jagged array.
Once the array is created, you can initialize it with values.

50
Divya S R , Assistant Professor, Dept. of Computer Application

Alternatively, you can also initialize an array as follows:


int myarray[][] = new int[][]
{
new int[] { 1, 2, 3 };
new int[] { 4, 5, 6, 7 };
new int[] { 8, 9 };
};
Yet another way of initializing a Jagged array is by omitting the first
new operator as shown below:
int[][]myarray ={
new int[] { 1, 2, 3 };
new int[] { 4, 5, 6, 7 };
new int[] { 8, 9 };
};
As you can see above, the new operator is omitted and the array is initialized as
well as declared in the same statement.

You can also omit all the new operators all together and have a
declaration and initialization statement as shown below.
int[][] arr = {
{ 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 8, 9 }
};
The program below initializes a ragged array by assigning initial values to
each row. Here each row of the array is initialized to the column values.

Example:
import [Link].*;
import [Link].*;
public class Main
{
public static void main(String[] args)
{
// Declaring a 2-D array with 3 rows

51
Divya S R , Assistant Professor, Dept. of Computer Application

int arr[][] = new int[3][];


// create a jagged array
arr[0] = new int[]{99,100,101};
arr[1] = new int[]{199,200};
arr[2] = new int[]{299,300,301,302,303};
// Displaying the elements of 2-D Jagged array
[Link]("Elements of 2-D Jagged Array");
for (int i = 0; i < [Link]; i++)
{
for (int j = 0; j < arr[i].length; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
Output
Elements of 2-D Jagged Array

99 100 101

199 200

299 300 301 302 303

The ArrayList classes


An ArrayList class is a resizable array, which is present in the [Link] package.
While built-in arrays have a fixed size, ArrayLists can change their size
dynamically. Elements can be added and removed from an ArrayList whenever
there is a need, helping the user with memory management.

Example:
import [Link];
public class Main
{
public static void main(String[] args)
{

52
Divya S R , Assistant Professor, Dept. of Computer Application

ArrayList<String> cars = new ArrayList<String>();


[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
[Link](cars);
}
}
Output: [Volvo, BMW, Ford, Mazda]

Methods of ArrayList class

1) add( Object o): This method adds an object o to the arraylist.


Example: [Link]("hello");
This statement would add a string hello in the arraylist at last position.

2) add(int index, Object o): It adds the object o to the array list at the given
index.
Example: [Link](2, "bye");
It will add the string bye to the 2nd index (3rd position as the array list starts
with index 0) of array list.

3) remove(Object o): Removes the object o from the ArrayList.


Example: [Link]("Chaitanya");
This statement will remove the string “Chaitanya” from the ArrayList.

4) remove(int index): Removes element from a given index.


Example: [Link](3);
It would remove the element of index 3 (4th element of the list – List starts with
o).

5) set(int index, Object o): Used for updating an element. It replaces the
element present at the specified index with the object o.
Example: [Link](2, "Tom");

53
Divya S R , Assistant Professor, Dept. of Computer Application

It would replace the 3rd element (index =2 is 3rd element) with the value Tom.

6) int indexOf(Object o): Gives the index of the object o. If the element is not
found in the list then this method returns the value -1.
Example: int pos = [Link]("Tom");
This would give the index (position) of the string Tom in the list.

7) int size(): It gives the size of the ArrayList – Number of elements of the list.
Example: int numberofitems = [Link]();

8) boolean contains(Object o): It checks whether the given object o is


present in the array list if its there then it returns true else it returns false.
Example: [Link]("Steve");
It would return true if the string “Steve” is present in the list else we would get
false.

9) clear(): It is used for removing all the elements of the array list in one go.
The below code will remove all the elements of ArrayList whose object is obj.

54

You might also like