Java Module1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

JAVA BASICS

(MODULE - 1)

1
MODULE – I

INTRODUCTION TO JAVA:
 Java is a high-level, third generation programming language, like C, FORTRAN, Smalltalk, Perl,
and many others.
 Java language is called as an Object-Oriented Programming language .
 Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991.

HISTRORY OF JAVA:
 The history of Java starts with the Green Team. Java team members (also known as Green
Team), initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc.
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991.
 The small team of sun engineers was called as Green Team.
 James Gosling is known as the father of Java.
 Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
 After that, it was called Oak .
 In 1995, Oak was renamed as "Java".
Java was initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.

JAVA ARCHITECTURE
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the process of
interpretation and compilation. It defines all the processes involved in creating a Java program. Java
Architecture explains each and every step of how a program is compiled and executed.

steps for executing a Java program:


 In Java, there is a process of compilation and interpretation.
 The code written in Java, is converted into byte codes which is done by the Java Compiler.
 The byte codes, then are converted into machine code by the JVM.
 The Machine code is executed directly by the machine.

2
Byte Code:
Byte Code can be defined as an intermediate code generated by the compiler after the
compilation of source code(JAVA Program). This intermediate code makes Java a platform-
independent language.
Compiler converts the source code or the Java program into the Byte Code and secondly, the
Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java
Virtual Machine). The byte code is the common piece between the compiler(which creates it)
and the Interpreter (which runs it).

Components of Java Architecture


The Java architecture includes the three main components:

3
o Java Virtual Machine (JVM)
o Java Runtime Environment (JRE)
o Java Development Kit (JDK)

Java Virtual Machine(JVM)


The main feature of Java is WORA. WORA stands for Write Once Run Anywhere. The feature states
that we can write our code once and use it anywhere or on any operating system. Our Java program can
run any of the platforms only because of the Java Virtual Machine.

It is a Java platform component that gives us an environment to execute java programs. JVM's main task
is to convert byte code into machine code.
- JVM (Java Virtual Machine) is an abstract machine.
- It is called a virtual machine because it doesn't physically exist.
- It is a specification that provides a runtime environment in which Java bytecode can be executed.

The JVM performs the following main tasks:


o Loads code
o Verifies code
o Executes code
o Provides runtime environment

Java Runtime Environment (JRE)


- It is used to provide the runtime environment.
- It is the implementation of JVM.
- It physically exists. It contains a set of libraries and other files that JVM uses at runtime.

4
Java Development Kit (JDK):
- The Java Development Kit (JDK) is a software development environment which is used to
develop Java applications and applets.
- It physically exists.
- It contains JRE + development tools.

Tools of JDK:
 Appletviewer( It is used for viewing the applet)
 Javac(It is a Java Compiler)
 Java(It is a java interpreter)
 Javap(Java diassembler,which convert byte code into program description)
 Javah(It is for java C header files)
 Javadoc(It is for creating HTML document)
 Jdb(It is Java debugger)

JVM ARCHITECTURE
The JVM (Java Virtual Machine) architecture consists of several components that work together to
execute Java programs. Here is a high-level overview of the JVM architecture:
JVM consists of three main components.
1. ClassLoader.
2. Memory Area /Runtime Memory/Data Area.
3. Execution Engine.

5
1. Class Loader: The Class Loader component is responsible for loading Java class files into the JVM
at runtime. It performs tasks such as locating and reading class files, verifying their bytecode, and
defining the classes within the JVM.

2. Memory Area /Runtime Memory/Data Area.


The Runtime Data Area is the memory area where the JVM manages data during program execution.
It’s divided into five sub-areas.
a. Method area:
The Method Area stores class-level data, including the bytecode of methods, constant
pool, static variables, and method metadata.
b. Heap:
The Heap is the runtime data area where objects are allocated. It Stores information about all the
objects. So if a new object is created, after the creation that object is stored in the heap area.

c. Stack :
Each thread in the JVM has a Java Stack that stores method-specific data, including local
variables, method arguments, and method invocation records. It also manages method calls and
returns.
d. PC registers:
If the method that was executed was not a native method, the pc registers will store
information about the method’s next execution. A native method is a Java method that is implemented in
another programming language, such as C or C++.
e. Native method area:

6
If any native methods are accessed or executed, the native method area provides facility to
store them.

3. Execution Engine : The Execution Engine executes Java bytecode. It can employ different
techniques for bytecode execution, such as interpretation, Just-In-Time (JIT) compilation, or a
combination of both.

It consists of three parts:


1. Interpreter: The interpreter reads the bytecode line by line and converts it machine code.
2. Compiler: If the execution engine finds out that a method is repeated, it will use the JIT compiler
instead. As a result, the JIT compiler compiles and converts the entire bytecode into native machine code.
3. Garbage collector: The garbage collector runs in the background and it can remove unreferenced
objects and free the space in the heap area.

 Native Method Interface (JNI): The JNI allows Java programs to interact with native code
written in languages like C or C++. It provides a mechanism for Java code to call native methods
and access native libraries.
 JVM Languages: The JVM architecture supports languages other than Java through additional
compilers and runtime support. Examples include Kotlin, Scala, and Groovy, which can all be
compiled into bytecode and executed on the JVM.

JAVA BUZZWORDS:
The features of Java are also known as Java buzzwords. Java is an object oriented programming
language developed by Sun Microsystems of USA in 1991. Java is first programming language which is
not attached with any particular hardware or operating system. Program developed in Java can be
executed anywhere and on any system.

Features of Java are as follows:


1. Simple and small

7
2. Compiled and Interpreted
3. Platform Independent and portable
4. Object- oriented
5. Robust and secure
6. Distributed
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible

Simple and small


 Java is very small and simple language.
 Java does not use pointer and header files, goto statements, etc.
 It eliminates operator overloading and multiple inheritance.

Compiled and Interpreted


 Basically a computer language is either compiled or interpreted. Java comes together both these
approach thus making Java a two-stage system.
 Java compiler translates Java code to Bytecode instructions and Java Interpreter generate
machine code that can be directly executed by machine that is running the Java program.

Platform Independent and portable


 Java supports the feature portability. Java programs can be easily moved from one computer
system to another and anywhere.
 Changes and upgrades in operating systems, processors and system resources will not force any
alteration in Java programs. This is reason why Java has become a trendy language for
programming on Internet which interconnects different kind of systems worldwide.
 Java certifies portability in two ways.
o First way is, Java compiler generates the bytecode and that can be executed on any machine.
o Second way is, size of primitive data types are machine independent.

Object- oriented
 Java is truly object-oriented language. In Java, almost everything is an Object. All program code
and data exist in objects and classes.

8
Basic Concept of OOP(Object-Oriented Programming):
There are some basic concepts of object oriented programming as follows:
1. Object :
 Any entity that has state and behavior is known as an object.
 For example, a chair, pen, table, keyboard, bike, etc.
 It can be physical or logical.
 An Object can be defined as an instance of a class.
 An object contains an address and takes up some space in memory.
2. Class :
 Collection of objects is called class. It is a logical entity.
 A class can also be defined as a blueprint from which you can create an individual
object.
 Class doesn't consume any space.
3. Data abstraction :
Hiding internal details and showing functionality is known as abstraction
4. Data encapsulation :
 Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
 For example, a capsule, it is wrapped with different medicines.
 A java class is the example of encapsulation.
5. Inheritance :
 When one object acquires all the properties and behaviors of a parent object, it
is known as inheritance.
 It provides code reusability.
6. Polymorphism :
If one task is performed in different ways, it is known as polymorphism.
7. Dynamic binding :
 Dynamic binding is also referred to as a run-time polymorphism.
 In this type of binding, the functionality of the method call is not decided at
compile-time.
 In other words, it is not possible to decide which piece of code will be executed
as a result of a method call at compile-time

9
 Java comes with an extensive set of classes; organize in packages that can be used in program
by Inheritance. The object model in Java is trouble-free and easy to enlarge.

Robust and secure


 Java is a most strong language which provides many securities to make certain reliable code.
 Java also includes the concept of exception handling, which detain serious errors and reduces
all kind of threat of crashing the system.
 Security is an important feature of Java and this is the strong reason that programmer use this
language for programming on Internet.
 The absence of pointers in Java ensures that programs cannot get right of entry to memory
location without proper approval.

Distributed
Java is called as Distributed language for construct applications on networks which can contribute both
data and programs. Java applications can open and access remote objects on Internet easily. That means
multiple programmers at multiple remote locations to work together on single task

Multithreaded and Interactive


Multithreaded means managing multiple tasks simultaneously. Java maintains multithreaded programs.
That means we need not wait for the application to complete one task before starting next task. This
feature is helpful for graphic applications.

High performance
Java performance is very extraordinary for an interpreted language, majorly due to the use of
intermediate bytecode. Java architecture is also designed to reduce overheads during runtime.
The incorporation of multithreading improves the execution speed of program.

Dynamic and Extensible


 Java is also dynamic language.
 Java is capable of dynamically linking in new class, libraries, methods and objects.
 Java can also establish the type of class through the query building .
 It is possible to either dynamically link or abort the program, depending on the reply.
 Java program is support functions written in other language such as C and C++, known as native
methods.

10
UNDERSTANDING THE SEMANTIC AND SYNTAX DIFFERENCES BETWEEN C++ AND
JAVA
INDEX COMPARISON C++ JAVA
PARAMETER
1 Developed / C++ was developed by Bjarne Java was developed by James
Founded by Stroustrup at Bell Labs in 1979. Gosling at Sun Microsystems.
It was developed as an extension Now, it is owned by Oracle.
of the C language.
2 Programming It has support for both Java has support only for object-
model procedural programming and oriented programming models.
object-oriented programming.
3 Platform C++ is platform dependent. Java is platform-independent. It is
dependence based on the concept of Write
Once Run Anywhere.
4 Features supported C++ supports features like Java does not support features like
multiple inheritance, operator multiple inheritance, operator
overloading, Goto statements, overloading, Goto statements,
structures, pointers, unions, etc. structures, pointers, unions, etc.
5 Compiler and C++ uses compiler only. C++ is Java uses both compiler and
Interpreter compiled and run using the interpreter. Java source code is
compiler which converts source converted into bytecode at
code into machine code so, C++ compilation time. The interpreter
is platform dependent. executes this bytecode at runtime
and produces output. Java is
interpreted that is why it is
platform-independent.
6 Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads.
7 virtual keyword C++ supports virtual keyword so Java has no virtual keyword. We
that we can decide whether or can override all non-static
not to override a function. methods by default. In other
words, non-static methods are
virtual by default.

11
We can develop two types of java programs:
i. Stand-alone applications
o These are the programs written in Java to carry out certain tasks on a stand-alone
local computer.
o A stand-alone program that can be invoked from command line .
o A program that has a “main” method
ii. Web applets
o A program embedded in a web page , to be run when the page is browsed .
o A program that contains no “main” method

Executing a stand-alone java program involves two steps:


i. Compiling source code into bytecode program using javac compiler.
ii. Executing the bytecode program using java interpreter.

12
[ Two ways of using Java]

DATA TYPES :
 A data type is a scheme for representing values. An example is int which is the Integer, a data
type.
 Values are not just numbers, but any manner of data that a computer can process.
 The data type defines the kind of data that is represented by a variable.
 As with the keyword class, Java data types are case sensitive.

There are two types of data types


 primitive data type
 non-pimitive data type

In primitive data types, there are two categories


 numeric means Integer, Floating points
 Non-numeric means Character and Boolean

In non-pimitive types, there are three categories


 classes
 arrays

13
 interface

Following table shows the datatypes with their size and ranges.

1. Integer data type:


Integer datatype can hold the numbers. In Java, there are four types of integer as follows:
 byte
o Byte data type is an 8-bit signed two's complement integer.
o Minimum value is -128 (-2^7)
o Maximum value is 127 (inclusive)(2^7 -1)
o Default value is 0
o Example: byte a = 100 , byte b = -50
 short
o Short data type is a 16-bit signed two's complement integer.

14
o Minimum value is -32,768 (-2^15)
o Maximum value is 32,767 (inclusive) (2^15 -1)
o Default value is 0.
o Example: short s = 10000, short r = -20000
 int
o Int data type is a 32-bit signed two's complement integer.
o Minimum value is - 2,147,483,648.(-2^31)
o Maximum value is 2,147,483,647(inclusive).(2^31 -1)
o The default value is 0.
o Example: int a = 100000, int b = -200000
 long
o Long data type is a 64-bit signed two's complement integer.
o Minimum value is -9,223,372,036,854,775,808.(-2^63)
o Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
o Default value is 0L.
o Example: long a = 100000L, int b = -200000L

2. Floating point data type:


It is also called as Real number and when we require accuracy then we can use it. There are two types
of floating point data type.
 float
o Float data type is uses 32-bit.
o Default value is 0.0f.
o Example: float f1 = 234.5f
 double
o double data type uses 64-bit.
o Default value is 0.0d.
o Example: double d1 = 123.4

3. Character data type:


o It is used to store single character in memory.
o It uses 2 bytes storage space.
o Example: char ch ='A'

15
4. Boolean data type:
o It is used when we want to test a particular condition during the excution of the program.
o There are only two values that a boolean type can hold: true and false.
o Boolean type is denoted by the keyword boolean and uses only one bit of storage.
o Default value is false.
o Example: boolean one = true

5. Reference Data Types:


o Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Student etc.
o Class objects, and various type of array variables come under reference data type.
o Default value of any reference variable is null.
o A reference variable can be used to refer to any object of the declared type or any
compatible type.
o Example: Employee e1 = new Employee("Smith");

SIMPLE JAVA PROGRAM: Let's take our very first and a simple java program to understand
various terms required to write an application.

Example:
class FirstProgram
{
public static void main(String args[])
{
System.out.println(“ This is my first program”);
}
}

 System is a built-in class present in java.lang package. It contains pre-defined methods and
fields, which provides facilities like standard input, output, etc.

16
 out is a static final field (ie, variable)in System class which is of the type PrintStream (a built-
in class, contains methods to print the different data values). static fields and methods must be
accessed by using the class name, so ( System.out ).
 out here denotes the reference variable of the type PrintStream class.
 println() is a public method in PrintStream class to print the data values. Hence to access a
method in PrintStream class, we use out.println().

VARIABLES:
Variables are labels that express a particular position in memory and connect it with a data type .
Syntax:
dataType variableName;

Giving values to variables


A variable can be assigned with a value in either of the two ways
i. By using an assignment statement
Syntax:
variableName = initialValue;
or
dataType variableName = initialValue;

ii. Through keyboard

Input through keyboard using BufferedReader class


Example:
import java.io.*;
class read
{
public static void main(String args[]) throws Exception
{
InputStreamReader IR = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(IR);

System.out.println("Enter your name");


String nm = br.readLine( );

17
System.out.println("Good Morning " + nm);

}
}

Example:
import java.io.*;
class read1
{
public static void main(String args[]) throws Exception
{
InputStreamReader IR = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(IR);

System.out.println("Enter an integer :");


int a = Integer.parseInt(br.readLine( ));

System.out.println("Enter another integer :");


int b = Integer.parseInt(br.readLine ( ));

int c = a + b;
System.out.println("Result = " + c);

}
}
Input through keyboard using Scanner class:
Methods of Scanner class:

18
Example: Write a program to enter two numbers from keyboard using Scanner class and display
their sum.

import java.util.*;
class ReadScanner
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter first number :");


int a=sc.nextInt();

System.out.println("Enter second number :");


int b=sc.nextInt();

int c=a+b;
System.out.println("The result is "+c);
}
}
Example -2:
import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])

19
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();

System.out.println("Enter your name");


String name=sc.next();

System.out.println("Enter your fee");


double fee=sc.nextDouble();

System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);


sc.close();
}
}

Input through keyboard using Command line arguments:


Command line arguments are parameters that are supplied to the application program at the time of
invoking its execution. They must be supplied at the time of its execution following the file
name. In the main () method, the args is confirmed as an array of string known as string objects. Any
argument provided in the command line at the time of program execution, are accepted to the
array args as its elements. Using index or subscripted entry can access the individual elements of an
array. The number of element in the array args can be getting with the length parameter.
For example:
class Add
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(“Addition is=” + c);
}
}

20
output:
c:\javac Add.java
c:\java Add 5 2
7

DATA TYPE CONVERSION:


When you assign a value of one data type to another, the two types might not be compatible with each
other. If the data types are compatible, then Java will perform the conversion automatically known as
Automatic Type Conversion, and if not then they need to be cast or converted explicitly. For example,
assigning an int value to a long variable.

There are 2 different types of conversion in Java:


1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion or Widening:


 If the type conversion is conducted instantly through the compiler without having the
programmer’s involvement, the type conversion is known as implicit type conversion.
 The compiler fundamentally encourages every operand towards the data type of the biggest
operand.
 Implicit type conversion is also known as Widening conversion. These can be done
automatically because we are moving to wider data types.
 No loss of data occurs throughout the data conversion.
 If we have an expression with multiple (Mixed) integer sizes in it, if we have short and long,
whatever the largest integer size is, things will convert it to. So if we do an operation with a short
and a long, the short will be implicitly cast into along.
 If we perform an operation with mixed floating-point sizes, so we have a float and a double, they
will always go to the double because double is the largest floating-point size.
Example:
class TypeTest
{
public static void main(String args[])
{

21
float a=23.4f;
int b=12;
a=b;
System.out.println("a="+a+" b= "+b);
}
}
Output: a=12.0 b=12

Explicit Type Conversion or Narrowing


 The type conversion, which can be enforced through the programmer, is known as explicit type
conversion.
 Explicit type transformation can be known as typecasting.
 Loss of data might or might not occur during data conversion.
 If we want to assign a value of a larger data type to a smaller data type we perform explicit
type casting or narrowing.
 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.

Example:
class TypeTest
{
public static void main(String args[])
{
float a=34.5f;
int b=12;
b=(int)a;
System.out.println("a="+a+" b= "+b);
}
}

22
Output: a=34.5 b=34

SCOPE OF VARIABLES:
There are three types of variables in java
 local variable :
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
 Local variables are visible only within the declared method, constructor or block.
 Access modifiers cannot be used for local variables.
 There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.
 instance variable :
 Instance variables are declared in a class, but outside a method, constructor or any block.
 When a space is allocated for an object in the heap, a slot for each instance variable value
is created.
 Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
 Access modifiers can be given for instance variables.
 static variable
 Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
 Static variables are created when the program starts and destroyed when the program
stops.

CONSTANTS:
Constant means fixed value which is not change at the time of execution of program. In Java, there are
two types of constant as follows:

23
Numeric Constants
o Integer constant : Example- 23 411 , 7,00,000
o Real constant : Example – 0.0234 , 0.777 ,-1.23
Character Constants
o Character constant : Example – 'A‘ , '7‘ ', '\‘
o String constant :Example - “WELCOME” , “END OF PROGRAM”

Symbolic constant:
In Java program, there are many things which are required repeatedly and if we want to make changes
then we have to make these changes in whole program where this variable is used. For this purpose, Java
provides ̳final‘ keyword to declare the value of variable as follows:

Syntax:
final type Symbolic_name=value;
Example:
final float PI=3.1459

Backslash character constant:


Java support some special character constant which are given in following table.

Constant Importance
\b Back space
\t Tab
\n New Line
\\ Back slash
'\'' Single Quote
'\'” Double Quote

KEYWORDS:
o Keywords are important part of Java.
o Java language has reserved 50 words as keywords.
o Keywords have specific meaning in Java.
o We cannot use them as variable, classes and method.
Following table shows keywords.

24
OPERATORS
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs to operate
data and variables. They frequently form a part of mathematical or logical expressions.

Categories of operators are as follows:


 Arithmetic operators
Arithmetic operators are used to make mathematical expressions and the working out as same in
algebra.
Example: +, _, *, / etc..
 Logical operators :
When we want to form compound conditions by combining two or more relations, then we can
use logical operators.
Example: ||(logical OR), &&(logical AND), !(logical NOT) etc.
 Relational operators
When evaluation of two numbers is performed depending upon their relation, assured decisions
are made. The value of relational expression is either true or false.
Example: < , > , >=, <=, != etc.
 Assignment operators
Assignment Operators is used to assign the value of an expression to a variable and is also called
as Shorthand operators.
Variable_name binary_operator = expression
Example: A=A+1 (A+=1) , A=A/(B+1) i.e A/=(B+1) etc.
 Conditional operators
The character pair ?: is a ternary operator of Java, which is used to construct conditional
expressions of the following form:
25
Expression1 ? Expression3 : Expression3
 Increment and decrement operators
The increment operator ++ adds 1 to a variable. Usually the variable is an integer type .
 Bit wise operators
Bit wise operator execute single bit of their operands.
Example: |(Bitwise OR), &(Bitwise AND), <<(left shift), >>(right shift) etc.

Special Operators:
i. Instanceof Operator
The instanceof is an object reference operator and returns true is the object on the left-hand
side is an instance of the class given on the right-hand side. This operator allows us to
determine whether the object belongs to a particular class or not.
Example:
person instanceof student
is true if the object person belongs to the class student, otherwise it is false.
ii. Dot Operator
The dot operator ( . ) is used to access the instance variavles and methods of class objects.
Example:
person1.age , student1. Roll etc
Separators
Separators are symbols. It shows the separated code.
Example: , ,., ; etc

Operator Precedence in Java:


An arithmetic expression without any parentheses will be calculated from left to right using the rules of
precedence of operators.
There are two priority levels of arithmetic operators are as follows:
(a) High priority (* / %)
(b) Low priority (+ -)

Mathematical Functions
Mathematical functions such as cos, sqrt, log etc are frequently used in analysis of real life problems.
Java supports these basic mathematical functions through Math class defined in the java. lang package.

26
Syntax:
Math. function_name( )
Example:
class math1
{
Public static void main(String args[ ])
{
double x;
x = Math.max(22, 46);
System.out.println(“ The maximum number is :” + x );
x = Math.sqrt(64);
System.out.println(“Square root is :” + x);
x = Math.pow(2, 3);
System.out.println(“ The power is :” + x);
}
}

CONTROL STATEMENTS IN JAVA:


All programs are seen as composed of three control structures:
 "Sequence" : ordered statements or subroutines executed in sequence.
 "Selection" : one or a number of statements is executed depending on the state of the program.
This is usually expressed with keywords such as if..then..else..endif.
 "Iteration" : a statement or block is executed until the program reaches a certain state, or
operations have been applied to every element of a collection. This is usually expressed with
keywords such as while, for or do..until.

Conditional Statement:
Selection statement is also called as Decision making statements because it provides the decision
making capabilities to the statements.

In selection statement, there are two types:


 if statement :
Syntax:
If (condition)

27
{
True - Statement block;
}
else
{
False - Statement block;
}
Example:
 Write a program to find out the greatest number among three number using nested if (taking input
through Command line argument).

public class GDemo


{
public static void main(String arg[])
{
int a,b,c;
a=Integer.parseInt(arg[0]);
b=Integer.parseInt(arg[1]);
c=Integer.parseInt(arg[2]);
if(a>b)
{
if(a>c)
System.out.println(a+"is greatest");
else
System.out.println(c+"is greatest");
}
else
{
if(b>c)
System.out.println(b+"is greatest");
else
System.out.println(c+"is greatest");
}
}//End of main

28
}//End of class
 switch statement :
Syntax:
switch(condition)// condition means case value
{
case value-1:
statement block1;
break;
case value-2:
statement block2;
break;
....

...
default:
statement block-default;
break;
}
statement a;

Example:
Enter a number (0-9) through command line argument and print in words using switch statement.

public class SwitchDemo


{
public static void main(String arg[])
{ int a;
a=Integer.parseInt(arg[0]);
switch(a)
{
case 0:
System.out.println("ZERO");
break;

29
case 1:
System.out.println("ONE");
break;
case 2:
System.out.println("TWO");
break;
case 3:
System.out.println("THREE");
break;
case 4:
System.out.println("FOUR");
break;
case 5:
System.out.println("FIVE");
break;
case 6:
System.out.println("SIX");
break;
case 7:
System.out.println("SEVEN");
break;
case 8:
System.out.println("EIGHT");
break;
case 9:
System.out.println("NINE");
break;
default:
System.out.println("OUT OF RANGE");
}
}
}

30
Loop Statement:
The process of repeatedly executing a statements and is called as looping. The statements may be
executed multiple times (from zero to infinite number). If a loop executing continuous then it is called as
Infinite loop. Looping is also called as iterations.

In Iteration statement, there are three types of operation:


 for loop
Syntax:
for(initialization;condition;iteration)//iteration means increment/decrement
{ Statement block; }

 while loop
Syntax:
While(condition)
{
Statement block;
}

 do-while loop
Syntax:
do
{
Statement block;
}
While(condition);

Example: Write a program in java to print the following pattern


1
121
12321
1234321
123454321

public class Triangle

31
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
for(int s=1;s<=5-i;s++)
System.out.print(" ");
for(int j=1;j<=i;j++)
System.out.print(j);
for(int j=i-1;j>=1;j--)
System.out.print(j);
System.out.println();
}
}
}

Example:
// Program to check if a number entered through keyboard is prime or not
import java.util.Scanner;
public class PrimeDemo
{

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
int num= sc.nextInt();

boolean flag = false;


for (int i = 2; i <= num / 2; ++i)
{
if (num % i == 0)
{
flag = true;

32
break;
}
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
WRAPPER CLASSES
 we may come across situations where we need to use objects instead of primitive data types. In order
to achieve this, Java provides wrapper classes.
 Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.
 All the wrapper classes are subclasses of the abstract class Number.
 The eight classes of java.lang package are known as wrapper classes in java. The list of eight
wrapper classes are given below:

 The object of the wrapper class contains or wraps its respective primitive data type. Converting
primitive data types into object is called boxing, and this is taken care by the compiler.

33
 The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing.
 The Number class is part of the java.lang package.

Example of boxing and unboxing


public classTest
{
public static void main(Stringargs[])
{
Integer x =5; // boxes int to an Integer object
x = x+10; // unboxes the Integer to a int
System.out.println(x);
}
}

When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x
is unboxed so that they can be added as an integer.

Wrapper class Example: Wrapper to Primitive


public class WrapperDemo
{
public static void main(String args[])
{
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int
int j=a; //unboxing,

System.out.println(a+" "+i+" "+j);


}
}

Example of Float wrapper class


public class WrapperDemo1
{

34
public static void main(String[] args)
{
float f = 10.10f;
Float obj1 = new Float(f);

System.out.println(obj1);

double d = 10.10;
Float obj2 = new Float(d);
System.out.println(obj2);

Float obj3 = newFloat("25.34");


System.out.println(obj3);
}
}
Example:
import java.io.*;

class WrapperTest
{
public static void main(String args[]) throws Exception
{
InputStreamReader IR=new InputStreamReader(System.in);
BufferedReader BR=new BufferedReader(IR);

System.out.println("Enter the roll :");


int r=Integer.parseInt(BR.readLine());

System.out.println("Enter the mark1 :");


float m1=Float.parseFloat(BR.readLine());

System.out.println("Enter the mark2 :");


float m2=Float.parseFloat(BR.readLine());

35
float tot = m1+m2;

System.out.println("Enter the name :");


String n=BR.readLine();

System.out.println("ROLL = "+r+"NAME = "+n+" TOTAL MARK = "+tot);


}
}

ARRAYS IN JAVA:
 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.
 An array is a way to hold more than one value at a time.
 Java provides a data structure, the 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.

Types of Array in java


There are various types of array as below:
 One Dimensional Array
 Two Dimensional Array
 Three Dimensional Array

One Dimensional Array


Declaring Array Variables:
The syntax for declaring an array variable can be one of the following two ways:
Syntax:
dataType[ ]arrayRefVar;

36
or
dataTypearrayRefVar[ ];

Example:
int[ ]myArray;
or
int myArray[ ];

Creating Arrays:
You can create an array by using the new operator with the following syntax:
arrayRefVar = newdataType[arraySize];
or
dataType[]arrayRefVar = new dataType[arraySize];
or
dataType[]arrayRefVar = {value0, value1, ..., valuek};

Example: Initialization of array


class ArrayDemo
{
public static void main(String args[ ])
{
int i, j , k;
int array1[ ] = {10, 11, 12, 13};
int array2[ ] = new int[ ]{20, 21, 22, 23};
int [ ] array3 = new int[4];
array3[0] = 30;
array3[1] = 31;
array3[2] = 32;
array3[3] = 33;

System.out.println("FirstArray");
for(i=0; i<4; i++)
System.out.println(array1[i]);

37
System.out.println("SecondArray");
for(i=0; i<4; i++)
System.out.println(array2[i]);

System.out.println("ThirdArray");
for(i=0; i<4; i++)
System.out.println(array3[i]);
}
}

Example2:
public class testArray
{
public static void main(String[] args) {
int[] a = {10, 11, 12,13};

for (int i = 0; i<a.length; i++)


{
System.out.println(a[i] + " ");
}

int total = 0;
for (int i = 0; i<a.length; i++) {
total += a[i];
}

System.out.println("Total is " + total);


// Finding the largest element
int max = a[0];
for (int i = 1; i<a.length; i++)
{
if (a[i] > max)
max = a[i];
}

38
System.out.println("Max is " + max);
}
}

Example: Write a program to sort an array of numbers.


public class sortArray
{
public static void main(String[ ] args)
{
int[ ] a = {55, 43, 23,7,10, 71, 82,9};

int n = a.length ;
System.out.println(“The original array is :”);
for (int i = 0; i<n; i++)
System.out.println(a[i] + " ");
for (int i=0;i< n ; i++)
{
for (int j = i + 1 ; j < n ; j++)
{
if (a[i] < a[j])
{ int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}

System.out.println(“The sorted arrayis :”);


for (int i = 0; i< n; i++)
{
System.out.println(a[i] + " ");
}

39
}
}

The foreach Loops:


JDK 1.5 introduced a new for loop known as foreach loop or enhancedfor loop, which enables you to
traverse the complete array sequentially without using an index variable.

public class TestArray {


public static void main(String[] args) {
int[] a = {18, 25, 32, 30};

// Print all the array elements


for (int val: a) {
System.out.println(val);
}
}
}

Two dimensional and Three dimensional(Multi dimensional) array in java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java


i. dataType[][] arrayRefVar; (or)
ii. dataType [][]arrayRefVar; (or)
iii. dataType arrayRefVar[][]; (or)
iv. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java


int[][] arr=new int[3][3]; //3 row and 3 column

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

40
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

Example:
class ArrayDemo3
{
public static void main(String args[])
{
int a[]=new int[4];

a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;

System.out.println("Elements are :");


for(int val:a)
System.out.println(val);

System.out.println("Elements are :");


for(int x=0;x<a.length;x++)
System.out.println(a[x]);
}
}

41
Example:
import java.util.*;

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

Scanner sc=new Scanner(System.in);

System.out.println("Enter size of the array:");


int n=sc.nextInt();

int a[]=new int[n];

for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
int num=sc.nextInt();
a[i]=num;
}

System.out.println("Array elements are...");


for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}

JAVA STRINGS
Strings are used for storing text. A String variable contains a collection of characters surrounded by
double quotes:

Java provides three classes to represent a sequence of characters:

42
i. String
ii. StringBuffer
iii. StringBuilder.

The String class is an immutable class whereas StringBuffer and StringBuilder classes are
mutable.

STRING CLASS
A Java string is an instantiated object of the String class.

Creating & Using String Object


String stringName;
stringName = new String(“India”);

String firstName = new String(“Smith”);


int len = firstName.length( );

String Manipulation Methods:

Method Call Task Performed


S2 = S1.toLowerCase(); Converts the string S1 to all lowercase
S2 = S1.toUpperCase(); Converts the string S1 to all uppercase
S2 = S1. replace(‘x’ , ‘y’); Replace all appearance of x with y
S2 = S1. trim( ); Remove white spaces at the beginning and end of the string
S1.equals(S2); Returns ‘true’ if S1 is equal to S2.
S1.equalsIgnoreCase(S2); Returns ‘true’ if S1 = S2, ignoring the case of characters.
S1.length( ) Gives the length of S1
S1.charAt(n) Gives the nth character of S1
S1.compareTo(S2) Returns negative if S1 <S2, positive if S1 > S2 and zero if S1 is equal
S2.
S1.concat(S2) Concatenates S1 and S2
S1.subString(n) Gives substring starting from nth character.

43
S1.subString(n, m) Gives substring starting from nth character upto mth(not including mth )
String.ValueOf(p) Creates a string object of the parameter p
p.toStirng( ) Creates a string representation of the object p.
S1.indexOf(‘x’) Gives the position of first occurrence of ‘x’ in the string s1
S1.indexOf(‘x’ , n) Gives the position of ‘x’ that occurs after nth position in the string s1
String.ValueOf(variable) Converts the parameter value to string representation

Write a program enters a string and test all the method present in string class.
public class StringDemo
{
public static void main(String args[])
{
String s1="This is a Demo of String Class";
System.out.println("Length :"+ s1.length());
System.out.println("Charactr at :" + s1.charAt(0));

int start=10;
int end=14;
char c[]=new char[end-start];
s1.getChars(start,end,c,0);
System.out.println(c);

System.out.println("UpperCase :"+s1.toUpperCase());
System.out.println("LowerCase :"+s1.toLowerCase());
System.out.println("IndexOf :"+s1.indexOf('a'));
System.out.println(s1.indexOf('F'));
System.out.println(s1.indexOf('a',9));

System.out.println("Last Index Of"+s1.lastIndexOf('a'));

System.out.println("Java".compareTo("java") );

System.out.println("java".compareTo("Java") );

44
System.out.println("Jav".compareTo("Java") );

String s2=" Java ";


System.out.println(s2.trim().concat(" Core"));

if((s1.startsWith("This"))&&(s1.endsWith("Class")))
System.out.println("Java");
else
System.out.println("C");

String temp = s1.substring(0,4);


System.out.println("Temp="+temp);

String st1="Java";
String st2 = "java";
if(st1.equalsIgnoreCase(st2))
System.out.println ("They are equal");
else
System.out.println ("They are not equal");

String st3 = st1.replace('J','G');


System.out.println ("New String="+st3);
}
}

Output:
Length :30
Character at :T
Demo
Uppercase : THIS IS A DEMO OF STRING CLASS
Lowercase : this is a demo of string class
IndexOf :8
-1
27

45
Last Index Of :27
-32
32
-1
Java Core
Java
Temp = This
They are equal
New string = Gava

STRINGBUFFER CLASS
StringBuffer is a peer class of String. While String creates strings of fixed length, StringBuffer creates
strings of flexible length that can be modified in terms of both length and content. We can insert
characters and substrings in the middle of the string or append another string at the end.

The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class is same as
String except it is mutable i.e. it can be changed.

Method Task
s1.setCharAt(n, ‘x’) Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1. Insert(n, s2) Inserts the string s2 at the position n of the string
s1
s1.setLength(n) Sets the length of the string s1 to n. If n<
s1.length( ) s1 is truncated. If n> s1.length( ) zeros
are added to s1.

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

StringBuffer sb=new StringBuffer("Hello ");

sb.append("Java");//now original string is changed

46
System.out.println("Append :"+sb);//prints Hello Java

sb.insert(1,"Java");
System.out.println("Insert :" + sb);

sb.replace(1,3,"Java");
System.out.println("Replace :"+sb);

sb.delete(1,3);
System.out.println("Delete :"+sb);

sb.reverse();
System.out.println("Reverse :"+sb);

StringBuffer sb1=new StringBuffer();


System.out.println("Capacity :"+sb1.capacity()); //default 16

sb1.append("Hello");
System.out.println("Cpacity after appending :"+sb1.capacity()); //now 16

sb1.append("java is my favourite language");


System.out.println("New capacity :"+sb1.capacity()); //now (16*2)+2=34 i.e
(oldcapacity*2)+2

}
}
Output:

47
Example:
Enter a string from keyboard and check whether it is palindrome or not.
import java.io.*;
class pallindromeTest
{
public static void main(String args[]) throws Exception
{
int a[ ] = new int[10];

InputStreamReader ir = new InputStreamReader(System.in);


BufferedReader br = new BufferedReader(ir);

System.out.println("Enter a string:");
String s1 = br.readLine();

int length=s1.length();
char b[]=s1.toCharArray();
char c[]=new char[length];

int j = 0;
for(int i=length-1;i>=0;i--)
{
c[j]=b[i];
j++;
}

int count =0;


for(int i=0;i<length;i++)
{
if(c[i]==b[i])
count++;

48
}
if(count==length)
System.out.println(s1 + " is palindrome.");
else
System.out.println(s1 + " is not palindrome.");

}//End of main
}

Example 2:
WAP to test between = = and equals().
class equalsDemo
{
public static void main(String arg[])
{
String s1="Hello";
String s2=new String("Hello");
//Use of ==

if(s1==s2)
System.out.println("Same reference");
else
System.out.println("Different reference");

if(s1.equals(s2))
System.out.println("String same");
else
System.out.println("String different ");

}
}
Output:
Different reference

49
String same

Difference between String and StringBuffer classes:

STRINGBUILDER CLASS
 StringBuilder in Java represents a mutable sequence of characters.
 The String Class creates an immutable sequence of characters whereas the StringBuilder class
creates a mutable sequence of characters.
 The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
 It is available since JDK 1.5.
 The function of StringBuilder is very much similar to the StringBuffer class, as both of them
provide an alternative to String Class by making a mutable sequence of characters.
 However, the StringBuilder class differs from the StringBuffer class on the basis of
synchronization.
 The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer
class does.
 If synchronization is required then it is recommended that StringBuffer be used.
 String Builder is not thread-safe and high in performance compared to String buffer.

50
Important methods of StringBuilder class
Method Description
public StringBuilder append(String s) It is used to append the specified string with this
string.
public StringBuilder insert(int offset, String s) It is used to insert the specified string with this
string at the specified position.
public StringBuilder replace(int startIndex, int It is used to replace the string from specified
endIndex, String str) startIndex and endIndex.
public StringBuilder delete(int startIndex, int It is used to delete the string from specified
endIndex) startIndex and endIndex.
public StringBuilder reverse() It is used to reverse the string.
public int capacity() It is used to return the current capacity.
public int length() It is used to return the length of the string i.e. total
number of characters.
public char charAt(int index) It is used to return the character at the specified
position.
public String substring(int beginIndex, int It is used to return the substring from the specified
endIndex) beginIndex and endIndex.
public String substring(int beginIndex) It is used to return the substring from the specified
beginIndex.

Example:
Write a program in Java to create object using StringBuilder class and demonstrate the usages of
various methods of StringBuilder class.

Program:
class StringBuilderDemo
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");

51
sb.append("Trident");
System.out.println(sb);

sb.insert(1,"Java");
System.out.println(sb);

sb.replace(10,16,"TACT");
System.out.println(sb);

sb.delete(1,5);
System.out.println(sb);

sb.reverse();
System.out.println(sb);
}
}

Output:

Comparison among String, StringBuffer and StringBuilder classes:

52

You might also like