0% found this document useful (0 votes)
7 views

JAVA UNIT 1

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JAVA UNIT 1

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

CORE COURSE – V: JAVA PROGRAMMING 23UCSCC43

UNIT – I
Introduction: Review of Object Oriented Concepts – History of Java – Java
Buzzwords – JVM Architecture – Data Types – Variables – Scope and Life Time of
Variables – Arrays – Operators – Control Statements – Type Conversion and Casting –
Simple Java Program – Constructors – Methods – Static Block – Static Data – Static
Method String and String Buffer Classes.

Review of Object Oriented Programming Concepts


1. Object Oriented Programming is a paradigm that provides many concepts such
as inheritance, data binding, polymorphism etc.
2. Simula is considered the first object-oriented programming language. The
programming paradigm where everything is represented as an object is known
as a truly object-oriented programming language.
3. Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table, etc. Object-oriented
programming is a methodology or paradigm used to design a program using classes
and objects. It simplifies the software development and maintenance by providing some
concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Object
 Any entity with a state and behavior is known as an object, such as a chair, pen,
table, keyboard, bike, etc. It can be physical and logical.

Class
 Class is a user-defined data type. Class is a collection of data members and
member functions. It can be created using the keyword “class”.
Inheritance
 Deriving a new class (Sub Class) from an old class (Super Class) is called Inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
Benefits of Inheritance
1. One of the key benefits of inheritance is to minimize the amount of duplicate code
in an application by sharing common code amongst several subclasses.
2. Inheritance can also make application code more flexible to change because classes
that inherit from a common superclass can be used interchangeably. If the return
type of a method is superclass
3. Reusability - facility to use public methods of a base class without rewriting the same.
4. Extensibility - extending the base class logic as per the business logic of the
derived class.
Polymorphism
 When one task is performed in different ways i.e. known as polymorphism.
 For example: to draw different shapes using the same method.
 In Java, we use method overloading and method overriding to achieve polymorphism.
Abstraction
 Hiding internal details and showing functionality is known as abstraction.
 For example: phone call, we don't know the internal processing.
 In Java, we use abstract classes and interfaces to achieve abstraction.
Encapsulation
 Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
 For example: a capsule, is wrapped with different medicines.
 A Java class is an example of encapsulation.

***************************
History of JAVA

 Java is a high-level programming language originally developed by Sun


Microsystems and released in 1991.
 Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX. So java is platform independent.
 Java was designed for the development of software for consumer electronic
devices like TVs, VCRs, toasters and such other electronic devices.
 1990 → A team of Sun Microsystems headed by James Gosling was decided to
develop a special software that can be used to manipulate consumer electronic
devices.
 1991 → James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers is called the Green Team.
The team announced a new language named “oak”.
 1992 → The team demonstrated the application of their new language to control
a list of home applications.
 1993 → The team known as Green Project team came up with the idea of
developing web applets.
 1994 → The team developed a web browser called “HotJava” to locate and run
applet programs on internet.
 1995 → Oak was renamed Java. Initially
developed by James Gosling at Sun
Microsystems
 1996 → Sun releases Java Development Kit 1.0.
 1997→ Sun releases Java Development Kit 1.1.
 1998 → Sun releases the Java 2 with
version 1.2.
 1999 → Sun releases standard edition (J2SE)
and enterprise edition(J2EE).
 2000 → J2SE with SDK(software
development kit) 1.3 was released.
 2002 → J2SE with SDK 1.4 was released.
 2004 → J2SE JDK 5.0 was released. This is known as J2SE 5.0.

Java Platforms / Editions


There are 4 platforms or editions of Java

• Java Standard Edition: - Java Standard Edition, also known as J2SE / JSE is the java platform (Any
hardware or software environment in which a program runs is known as a platform.) for developing
client-side application which runs on desktop, and applets which run on web browser.
Core Java + JDBC is the part of Java Standard Edition (J2SE / JSE).

• Java Enterprise Edition : - Java Enterprise Edition, also known as J2EE / JEE is the java platform
built on the top of Java SE , which is used to develop enterprise- oriented server applications.(Server side
applications include servlets, which are java programs that are similar to applets but run on a server
rather than a client.)
Servlets + JSPs are the part of Java Enterprise Edition.

• Java Micro Edition: - Java Micro Edition, also known as J2ME / JME is the java platform which is
also built on Java SE. It is mainly used to develop mobile applications.

• Java FX: - Java FX, also known as Java Flex is used to develop rich internet applications. It uses
light-weight user interface API.

JAVA BUZZ Words (or) Features of JAVA


They are also known as java buzzwords. The Java Features given below are simple and easy to
understand.

1. Simple
2. Object-Oriented
3. Portable
4. Platform-independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Simple
 Java is very easy to learn, and its syntax is simple, clean, and easy to understand.
2. Object-oriented
 Java is an object-oriented programming language.
 Everything in Java is an object.
 Object-oriented means we organize our software as a combination of different types of
objects that incorporate both data and behavior.
 Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

3. Portable
 Java is portable because it allows you to carry the Java bytecode to any platform. It doesn't
require any implementation.

4. Platform – Independent
 Java is a write-once, run-anywhere language.
 Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc.
 Java code is compiled by the compiler and converted into bytecode.
This bytecode is a platform-independent code because it can be run on multiple platforms,Write Once
and Run Anywhere (WORA) which means that we can develop applications on one environment (OS) and
run on any other environment without doing any modification in the code.
 Below diagram explains the platform independence feature of Java-Portable.
5. Secured
 Java is best known for its security.
 Java is secured because of the following
o No explicit Pointer
o Run inside a virtual machine sandbox
o Classloader
o Bytecode Verifier
o Security Manager
6. Robust
Java is robust because:
 It uses strong memory management.
 There is a lack of pointers.
 Java provides automatic garbage collection.
 There are exception-handling and the type checking mechanism in Java.
7. Architecture Neutral
 Java is architecture-neutral because there are no implementation-dependent features,
for example, the size of primitive types is fixed.
8. Dynamic
 Java is a dynamic language.
 It supports the dynamic loading of classes.
 It means classes are loaded on demand.
10. High Performance
 Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.
11. Multithreaded
 A thread is like a separate program, executing concurrently.
 We can write Java programs that deal with many tasks at once by defining multiple
threads.
12. Distributed
 Java is distributed because it facilitates users to create distributed applications in Java.
 RMI and EJB are used for creating distributed applications.
***********************

JVM Architecture (or) JAVA Bytecode


Bytecode
 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.
Working Principle
 The compiler converts the source code or the Java program into the Byte Code (or
machine code)
 Next, 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).

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides


runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by
Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the
java class, an instance of JVM is created.

The JVM performs the following main tasks:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The
Java Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment.

JDK is an acronym for Java Development Kit. 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.
JVM provides definitions for the:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

JVM Architecture
1) Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is
loaded first by the classloader. There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like
java.lang package classes, java.net package classes, java.util package classes, java.io
package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader
of System classloader.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It
loads the classfiles from classpath. By default, classpath is set to current directory.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method
data, the code for methods.

3) Heap
It is the runtime data area in which objects are allocated.

4) Stack

 Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
 Each thread has a private JVM stack, created at the same time as thread.
 A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.

6) Native Method Stack

It contains all the native methods used in the application.


7) Execution Engine:It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the
amount of time needed for compilation. Here, the term "compiler" refers to a translator
from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific
CPU.
4. 8) Java Native Interface :Java Native Interface (JNI) is a framework which provides an
interface to communicate with another application written in another language like C, C++,
Assembly etc. Java uses JNI framework to send output to the Console or interact with OS
libraries.

JAVA Data Types –

Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.
Java Primitive data types:

1. boolean data type


2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type

Boolean Data Type


In Java, the boolean data type represents a single bit of information with two possible states: true or false.
It is used to store the result of logical expressions or conditions.

Byte Data Type


The byte data type in Java is a primitive data type that represents an 8-bit signed two's complement
integer. It has a range of values from -128 to 127. Its default value is 0.

Short Data Type


The short data type in Java is a primitive data type that represents a 16-bit signed two's
complement integer. It has a range of values from -32,768 to 32,767.

Int Data Type


The int data type in Java is a primitive data type that represents a 32-bit signed two's
complement integer. It has a range of values from -2,147,483,648 to 2,147,483,647. The int data
type is one of the most commonly used data types in Java and is typically used to store whole
numbers without decimal points. Its default value is 0.We can make integers long by appending
the letter L or 1 at thr end of the number.Ex.123L.

Long Data Type


The long data type in Java is a primitive data type that represents a 64-bit signed two's
complement integer. It has a wider range of values than int, ranging from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Float Data Type


The float data type in Java is a primitive data type that represents single-precision 32-bit IEEE
754 floating-point numbers. It can represent a wide range of decimal values, but it is not suitable
for precise values such as currency. Its default value is 0.0F.
Double Data Type

The double data type in Java is a primitive data type that represents double-precision 64-bit
IEEE 754 floating-point numbers. Its default value is 0.0d.
Char Data Type

The char data type in Java is a primitive data type that represents a single 16-bit Unicode
character. It can store any character from the Unicode character set, that allows Java to support
internationalization and representation of characters from various languages and writing
systems.
Type Size Minimum value Maximum value
Byte One byte -128 127
Short Two bytes -32,768 32,767
Int Four bytes -2,147,483,648 2,147,483,647
Long Eight - 9,223,372,036,854,77
bytes 5,
9,223,372,036,854,775, 807
8
08

Type Size Minimum value Maximum


value
Float 4 bytes 3.4e-038 1.7e+0.38
double 8 bytes 3.4e-038 1.7e+308

Non-Primitive Data Types in Java


 In Java, non-primitive data types, also known as reference data types, are used to store
complex objects rather than simple values.
 reference data types store references or memory addresses that point to the location of
the object in memory manipulated in Java programs.
Class
 Classes are used to create objects, which are instances of the class.
 A class defines the properties and behaviors of objects, including variables (fields) and
methods.

For example, you might create a Person class to represent a person, with variables for the
person's name, age, and address, and methods to set and get these values.

Interface
 An interface defines a contract for what a class implementing the interface must provide,
without specifying how it should be implemented.
 Interfaces are used to achieve abstraction and multiple inheritance in Java, allowing
classes to be more flexible and reusable.
Arrays
 that allow you to store multiple values of the same type in a single variable.
 Arrays have a fixed size, which is specified when the array is created, and can be accessed
using an index.
 Arrays are commonly used to store lists of values or to represent matrices and other
multi-dimensional data structures.
Enum
Java also includes other non-primitive data types, such as enums and collections.
 Enums are used to define a set of named constants, providing a way to represent a fixed
set of values.
 Collections are a framework of classes and interfaces that provide dynamic data
structures such as lists, sets, and maps, which can grow or shrink in size as needed.

JAVA Variables
A variable is an identifier that denotes a storage location used to store a data value.
Variable names may consist of alphabets, digits, the underscore( _ ) and dollar
characters, subject to the following conditions:
 They must not begin with a digit.
 Uppercase and lowercase are distinct.
 It should not be a keyword.
 White space is not allowed.
 Variable names can be of any length.
Declaration of variable

type variable1,variable 2,…….variable n


 A variable is the name of a reserved area allocated in memory.

int data=10;//Here data is variable

Types of Variables and its Scope


There are three types of variables in Java:
1. Local variable
2. Instance variable
3. Static variable
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.
 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.
 Access specifiers cannot be used for local variables.
A local variable cannot be defined with "static" keyword.
Scope: Within the block it is declared.
 Lifetime: Until control leaves the block in which it is declared.
Instance Variable
 A variable declared inside the class but outside the body of the method, is called an
instance variable.

 It is called an instance variable because its value is instance-specific and is not shared
among instances.

 Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed.

 Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present
throughout the class.

 Access modifiers can be given for instance variables.

 The instance variables are visible for all methods, constructors and block in the class. It
is recommended to make these variables as private. However, visibility for subclasses
can be given for these variables with the use of access modifiers.

 Instance variables have default values.numbers, the default value is 0,

Booleans it is false,

Object references it is null.

 Values can be assigned during the declaration or within the constructor.

 Instance variables cannot be declared as static.


 Scope: Throughout the class except in the static methods.
 Lifetime: Until the object of the class stays in the memory.
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.
 Scope: Throughout the class.
 Lifetime: Until the end of the program.
Example
public class varible
{
static int m=100;//static variable void
method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Constants in Java

A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.
Syntax
Modifier final dataType variableName = value;

Modifier static final dataType variableName = value;

Arrays
 An array is a collection of similar type of elements which has 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.
Types of Array
There are two types of array.
 One Dimensional Array
 Multidimensional Array

Creating An Array
Creation of array includes three steps:
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.

One Dimensional Array


A list of items can be given one variable name using only one subscript and such
variable is called a single-subscripted variable or a one-dimensional array.

Declaration of one-dimensional array:


Arrays in java may be declared in two
forms. Form 1: type arrayname[ ];
Form 2: type[ ] arrayname;
Ex:
int mark[]; int[]mark;
Creation of one-dimensional array
Arrays are created by using new operator. The general form is
arrayname = new type[size];
Ex: int mark = new int[10];

Initialization of one-dimensional array:


Values are assigned to the array by specifying the subscript.
Arrayname [subscript] = value;
Ex: mark[0] = 65;
mark[1]=75;
An array may also be initialized when they are declared.
type arrayname[ ] = {list-of-values};
The list-of-values are separated by comma and surrounded by curly braces. The memory for
the array is allocated by the compiler based on the number of values given.
Ex: int x[] = {25,35,15,5,55};

Array length : In java, all arrays store the allocated size in a variable named length.
To know the size of an array, it can be accessed as
arrayname.length

Example: int a size=a.length;


Two-Dimensional Arrays
To store the values in a table form then two dimensional array is used. Two
subscript are needed to access a value in two dimensional array.

Creation of two-dimensional array


Arrays are created by using new operator. The general form
is arrayname = new type[row][col];
Ex: myarray = new int[3][2];
Int myarray [] []=new int [3][2];

Initialization of two-dimensional array:


Values are assigned to the array by specifying the subscript.
arrayname[subscript1][subsrcipt2] = value;
Ex: myarray [2][2] = 15;

An array may also be initialized when they are


declared.
type arrayname[ ][ ] = {list-of-values};
The list-of-values are separated by comma and surrounded by curly braces. The
memory for the array is allocated by the compiler based on the number of values
given.
Ex: int x [ ][ ] = {25,35,15,5,55,45};

Variable Size Arrays


Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a
two-dimensional array as follows.
int x[ ][ ] = new int [3]
[ ]; x[0] = new int[2];
x[1] = new int[5];
x[2] = new int[3];
Operators in java
 Java supports a rich set of operators.
 An operator is a symbol that is used for manipulate data and variables.
 Operators are used in programs to manipulate data and variables.
o Arithmetic operators
o Relational operators
o Logical operators
o Assignment operators
o Increment and decrement operators
o Conditional operators
o Bitwise operators
o Special operators

Java operators are classified into number of categories.


➢ ARITHMETIC OPERATORS
Arithmetic operators are used to construct mathematical expressions as in algebra
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division

RELATIONAL OPERATORS
❖ Compares two quantities depending on their relation.
❖ Java supports six relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and is of the
following form:
ae-1 relational operator ae-2
where ae-1 and ae-2 are arithmetic expressions
LOGICAL OPERATORS

Java has three logical operators.


Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
A logical operator returns either TRUE or FALSE values.
Logical operator && and || are used to check compound condition (ie for
combining two or more relations)
When an expression combines two or more relational expressions then it is
called logical expression or a compound relational expression

ASSIGNMENT OPERATORS
 Used to assign the value of an expression to a variable.
 Assignment operators are usually in the form “=”.
v op=exp;

INCREMENT AND DECREMENT OPERATORS


❖ They are also called unary operator.
++ → Increment operator, add 1 to the operand
-- → Decrement operator, subtract 1 to the operand They
may also use to increment subscripted variables

CONDITIONAL OPERATORS
❖ The character pair ?: is used for conditional operator.
❖ It is also called as ternary operator.
General Form exp1 ? exp2: exp3
where exp1, exp2, exp3 are expressions
The operator ?: works as follows
exp1 is evaluated first, if its is true then the exp2 is evaluated. If
exp1 is false, exp3 is evaluated
BITWISE OPERATORS:
Bitwise operators are used to manipulate data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left.
❖ Bitwise operators may not to float or double.
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill

SPECIAL OPERATORS
❖ Java supports special operators
➢ Instance of operator
➢ Dot operator (or) member selection operator (.)

✓ Instance of operator:
❖ Instance of operator is an object reference operator.
❖ Allow us to determine whether the object belongs to a particular class or not.
❖ Return true, if the object on the left-hand side is an instance of the class
given on the right-hand side.

Dot operator
The dot operator (.) is used to access the instance variables and methods of class
objects.
It is also used to access classes and sub packages from a package.

CONTROL FLOW STATEMENTS


In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations.To solve this problem, java provides control
statements.
When a program breaks the sequential flow and jumps to another part of the code, it is
called branching. When the branching is based on a particular condition, it is known as
conditional branching. If branching takes place without any decision, it is known as
unconditional branching.

Types of Control Statements


In java, the control statements are classified as follows.
 Selection Control Statements ( Decision Making Statements )
 Iterative Control Statements ( Looping Statements )
 Jump Statements

Selection Control Statements


In java, the selection statements are also known as decision making statements or
branching statements. The selection statements are used to select a part of the program to
be executed based on a condition.
The following statements are known as control or decision making statements.

 if statement
 switch statement
 Conditional operator statement
IF Statement
The if statement is a powerful decision making statement and is used to control the
flow of execution of statements.
General form if (test expression)

The expression is first evaluated.


❖ Depending on the value of the expression is true or false, control is transfer to a
particular statement.
❖ The if statement are
1. simple if statement
2. if…else statement
3. Nested if…else statement
4. else if ladder
1.Simple If Statement
➢ If the test expression is true the statement block will be executed; otherwise the
execution will jump to the statement-x
➢ Statement block may be single statement or a group of statement.
General form
if (test expression)
{
statement-block;
}
statement-x;
Example
if (category == SPORTS)
{
marks = marks + bonus_marks;
}
System.out.println(marks);

2.The If…Else Statement


➢ If the test expression is true, then the true-block statements are executed.
➢ Otherwise, the false block statements are executed.
General form
if (test expression)
{
True block statements;
}
else
{
False block statements;
}
Statement-X;
Example

if (degree = = “BCA”)
{
points = points+500;
}
else
{
Points = points + 100;
}

3.Nested if …else statement


➢ Here if the condition-1 is false, the statement-3 will be executed; otherwise it
evaluates the condition-2.
➢ If the condition-2 is true, then statement-1 will be executed; otherwise the
statement -2 will be evaluated and then control is transferred to the statement-x.
General form

if (test condition1)
{
if (test condition2)
{
True
blockstatements-1;
}
else
{
False block
statement-2;
}
}
else
{
False block statements-3;
} Example
Statement-x; if (gender == “female”)
{
if (balance>5000)
{
Bonus = 0.03 *
balance;
}
else
{
Bonus = 0.02 *
balance;
}
}
else
{
Bonus = 0.01 * balance;
}
balance=balance + bonus;
4.Else if ladder
Else If ladder is a chain of ifs in which the statement associated with each else is an if.
The condition is evaluated from the top to downwards.
➢ As soon as the condition is true, then the statements associated with it are executed and
the control is transferred to the statement -x.
➢ When all the n condition is false, then the final else containing the default- statement
will be executed.

General form
If (condition-1)
statement-1; else if (condition-2)
statement -2; else if (condition-3)
statement -3;
…..
else if (condition n)
statement -n;
else
default-statement;

Example
If (marks>79)
grade=”honors”;
else if (marks>79)
grade=”first”;
else if (marks>79)
grade=”second”;
else if (marks>79)
grade=”third”;
else
grade=”fail”; // Default-stmt System.out.println(“grade=”+grade);

The Switch Statement


 It an multiway decision statement.
 The switch statement tests the value of a given variable against a list of case
 values.
 When a match is found, a block of statement associated with that case is executed.
 The expression is an integer expression or character known as case labels.
 Block1, block2 … are statements lists may contain zero or more statements.

 No need to put braces around each block

 Case labels end with a colon (:)


 The breakstatement at the end of each block signal the end of a particular case and causes an exit from
the switch statement, transferring the control to the statement -x following the switch.

 The default is an option case; it will be executed if the value of the expression does not match with any of
the case values.

 If not present, no action takes place when all matches fail and the control goes to the statement –x.

General form
switch(expression)
{
case value-1:
block-1
break; case value-2:
block-2
break; case value-3:
block-3
break;

Example
switch(expression)
{
case ‘1’:
System.out.println(“Monday”);
break; case ‘2’:
System.out.println(“Tuesday”);
break; case ‘3’:
System.out.println(“Wednesday”);
break;
………..
……….
default:
default-block break;
}
statement-x;

case ‘4’:
System.out.println(“Thursday”);
break;
………………
………………..
default:
System.out.println (“WRONG INPUT”);
break;

}
System.out.println(“ WELCOME TO THIS WEEK”.

3.CONDITIONAL OPERATORS
❖ The character pair ?: is used for conditional operator.
❖ It is also called as ternary operator.
General Form exp1 ? exp2: exp3 where exp1, exp2, exp3 are expressions
Example:
If(x<0)
Flag=0;
Else
Flag=1;
Flag =(x<0) ? 0 :1;

Iterative Control Statements


In java, the iterative statements are also known as looping statements or repetitive statements. The
iterative statements are used to execute a part of the program repeatedly as long as the given condition
is True. Using iterative statements reduces the size of the code, reduces the code complexity, makes it
more efficient, and increases the execution speed. Java provides the following iterative statements.

 while statement
 do-while statement
 for statement

while statement
The while loop loops through a block of code as long as a specified condition is true.
Syntax

while (condition) {

// code block to be executed

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less
than 5:

Example

int i = 0;

while (i < 5) {

System.out.println(i);

i++;

}
do-while statement:

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if th
condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do {
// code block to be executed

while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:

Example

int i = 0;
do {

System.out.println(i);

i++;

while (i < 5);


for statement
When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {

System.out.println(i);

Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the next
iteration. Java provides the following jump statements.

break
continue
return

break:

The break statement can also be used to jump out of a loop.

This example stops the loop when i is equal to 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

System.out.println(i);

}
CONTINUE:

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

System.out.println(i);

Return Statement

the return statement is used for returning a value when the execution of the block is completed.

Syntax:
The syntax of a return statement is the return keyword is followed by the value to be returned.

return returnvalue;

EXAMPLE:

public class SampleReturn1


{
/* Method with an integer return type and no arguments */
public int CompareNum()
{
int x = 3;
int y = 8;
System.out.println("x = " + x + "\ny = " + y);
if(x>y)
return x;
else
return y;
}
Type Casting and Conversion
Type Casting
 A data type is converted into another data type is known as type casting.
 It is used if we want to change the target data type to another data type.
 Remember that the destination data type must be smaller than the source data type.
Typr variable 1 =(type) variable 2; (): is a casting operator.

In Java, there are two types of casting:

Widening OR Automatic conversion− Converting a lower datatype to a higher datatype is known as


widening. In this case the casting/conversion is done automatically therefore, it is known as implicit
type casting. In this case both datatypes should be compatible with each other.

int x=30;
float y;
y=x; // y==30.000000.

Narrowing or Explicit conversion− Converting a higher datatype to a lower datatype is known as


narrowing. In this case the casting/conversion is not done automatically, We need to convert explicitly
using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both
datatypes need not be compatible with each other.

float x;
byte y;
...
...
y=(byte)x; //converting float(source) data type into byte(target) data type

s.NO TYPE CASTING TYPE CONVERSION

1. In type casting, a data type is converted Whereas in type conversion, a data type
s.NO TYPE CASTING TYPE CONVERSION

into another data type by a programmer is converted into another data type by a
using casting operator. compiler.

Type casting can be applied


Whereas type conversion can only be
2. to compatible data types as well
applied to compatible datatypes.
as incompatible data types.

In type casting, casting operator is


Whereas in type conversion, there is no
3. needed in order to cast a data type to
need for a casting operator.
another data type.

In typing casting, the destination data


Whereas in type conversion, the
type may be smaller than the source
4. destination data type can’t be smaller
data type, when converting the data
than source data type.
type to another data type.

Type casting takes place during the Whereas type conversion is done at the
5.
program design by programmer. compile time.

Type casting is also called narrowing Whereas type conversion is also called
conversion because in this, the widening conversion because in this, the
6.
destination data type may be smaller destination data type can not be smaller
than the source data type. than the source data type.

Whereas type conversion is less used in


Type casting is often used in coding and
7. coding and competitive programming as
competitive programming works.
it might cause incorrect answer.

Type casting is more efficient and Whereas type conversion is less efficient
8.
reliable. and less reliable.

WRITING SIMPLE JAVA PROGRAM:

A java program may contain many classes, of which only one class should contains main() method.

Documentation section
Package statements
Import statements
Interface statements
Class Definations
Main Method Class
{
Main Method Definations
}

Documentation section:

It consists of comment lines( program name, author, date,…….),


// - for single line comment.
/*----*/ - multiple line comments.
/**---*/ - known as documentation comment, which generated documentation automatically.

Java Single Line Comment:


The single line comment is used to comment only one line.

Syntax:
//This is single line comment
Java Multi Line Comment:
The multi line comment is used to comment multiple lines of code.
Syntax:
/*
This is
multi
line
comment
*/
Java Documentation Comment:
The documentation comment is used to create documentation API. To create documentation API, you
need to use javadoc tool.
Syntax:
/**
This is
documentation
comment
*/

Package statement:
This is the first statement in java file. This statement declares a package name and informs the compiler
that the class defined here belongs to this package.
Ex: - package student

Import statements:
This is the statement after the package statement. It is similar to # include in c/c++.
Ex: import java.lang.String
The above statement instructs the interpreter to load the String class from the lang package. Note:
• Import statement should be before the class definitions.
• A java file can contain N number of import statements.
Interface statements:
An interface is like a class but includes a group of method declarations.
Note: Methods in interfaces are not defined just declared.

Class definitions:
Java is a true oop, so classes are primary and essential elements of java program. A program can have
multiple class definitions.

Main method class:


Every stand-alone program required a main method as its starting point. As it is true oop the main method
is kept in a class definition. Every stand-alone small java program should contain at least one class with
main method definition.
A Simple Java Program:

To create a simple Java program, we need to create a class that contains the main method. Let's understand
the requirement first.
Requirements:
For executing any Java program, the following software or application must be properly installed.

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program

Creating Hello World Example:

class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Save the above file as Simple.java.
To compile: javac Simple.java
To execute: java Simple

Output:

Hello Java

Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into byte
code.

Parameters used in First Java Program:


 class keyword is used to declare a class in Java.
 public keyword is an access modifier that represents visibility. It means it is visible to all.
 static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it doesn't require creating an object to
invoke the main() method. So, it saves memory.
 void is the return type of the method. It means it doesn't return any value.
 main represents the starting point of the program.
 String[] args or String args[] is used for command line argument.
 System.out.println() is used to print statement. Here, System is a class, out is an object of
the PrintStream class, println() is a method of the PrintStream class.

Rules for writing JAVA programs:


 Every statement ends with a semicolon
 Source file name and class name must be the same.
Rules for file names:
 A source code file can have only one public class, and the file name must match the
public class name.

Introduction of classes:

A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
General form of class:
A class is declared by use of the class keyword.
class ClassName
{
VariableDeclaration-1; VariableDeclaration-2; VariableDeclaration-3;

VariableDeclaration-n;

returnType methodname-1([parameters list])


{
body of the method…
}
returnType methodname-2([parameters list])
{
body of the method…
}
returnType methodname-3([parameters list])
{
body of the method…
}
}// end of class

The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the class.
Example:
class Demo
{
int x=5;

void display()
{
System.out.println(“x value is: ”+x);
}}

Creating Objects:
An object in Java is essentially a block of memory that contains space to store all the instance variables.
Creating an object also known as instantiating an object. Objects in Java are created using the new
operator. The new operator creates an object of the specified class and returns a reference to that
object.
Syntax for object creation:
classname objectname; //declares a variable to hold the object reference
objectname = new classname( ); // Assigns the object reference to the variable

Accessing class Members:


To access members (fields and the methods) of an object use the dot (.) operator together with the
reference to an object.
The general syntax is as follows:
objectname.variablename;
objectname.methodname(parameter-list);
Example:

class Demo
{
int x;
int display()
{
System.out.println("X value is: "+x); return 0;
}
public static void main(String args[])
{
Demo D1=new Demo(); //creating objects
D1.x=10;
D1.display();
}
}
Output:
X value is: 10

METHODS IN JAVA:
A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and use it
many times.

Syntax

public static int methodName(int a, int b)


{
// body
Here,

 public static −modifier

 int − returntype

 methodName − name of the method

a, b − formalparameters

int a, int b − list ofparameters
Method Declaration

The method declaration provides information about method attributes, such as visibility, return-type, name,
and arguments. It has six components that are known as method header,
Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.

Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method

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. Some pre-defined methods
are length(), equals(), compareTo(), sqrt(), etc.

Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Example:

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9is

In the above example, we have used three predefined methods main(), print(), and max(). We have used
these methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class
that returns the greater of two numbers.

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.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we will define the method.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}

Output:
Enter the number: 45 num is odd

CONSTRUCTORS
NSTRUCTORS
A constructor is a special method that is used to initialize objects.
 The constructor is called when an object of a class is created.
 It can be used to set initial values for object
 The constructor name and the class name should be the same.
 The constructor doesn’t have a return type.
 All classes have constructors by default.

Rules for creating Java constructor


There are three rules defined for the constructor.
1. The constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized.

Types of Constructor
There are 2 types of constructor
 Default constructor: is the type of constructor with out any argument.
 Parameterized Constructor: is a constructor with one or more argument.

1. Default Constructor
 A constructor without parameters is called a default constructor.
 Default constructor is invoked if there is no constructor available in the class.
Syntax
Class_name(){
//code
}
Example
class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[]){ Bike1
b=new Bike1 ();
}
}

2. Parameterized Constructor
 A constructor which has a specific number of parameters is called a parameterized
constructor.
 The parameterized constructor is used to provide different values to distinct objects.
Syntax
Class_name(Parameters)
{
//code
}
Example
classStudent4
{
int id; Stringname;
Student4(int i,String n)
{
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}}

Output:

111Kara
222Arya
Static Keyword in JAVA

 Static keyword in Java is used for memory management.


 We can apply static keyword with variables, methods, blocks and nested classes.
The static can be:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block

Static Variable (or) Data


 If we declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects
 The static variable gets memory only once
 Static variables are shared among all instances of the class
 They can be accessed directly using the class name without needing to create
an instance of the class.
Example

Understanding the problem without static variable


class Student{ int rollno; String name;
String college="SVREC";
}
Suppose there are 500 students in our college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the common
property of all objects. If we make it static, this field will get the memory only once.

Example of static variable


class Student{
int rollno;//instance variable String name;
static String college ="SVREC";//static variable
//constructor Student(int r, String n){ rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[])
{
Student s1 = new Student(101,"Shyam");
Student s2 = new Student(102,"vinod");
//we can change the college of all objects by the single line of code
//Student.college="SVREC";
s1.display();
s2.display();
}
}
Output:
101 Shyam SVREC
102 vinod SVREC

Static Method
 If we apply a static keyword with any method, it is known as a static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of
a class.
 A static method can access static data members and can change their value of it.

Example

Static method
If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a
class.
 A static method can access static data member and can change the value of it.

Example of static method


//Java Program to demonstrate the use of a static method.
class Student{
int rollno; String name;
static String college = "SVR Engg College";
//static method to change the value of static variable static void change(){
college = "SVREC";
}
//constructor to initialize the variable Student(int r, String n){
rollno = r; name = n;
}
//method to display values void display(){
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object public class
TestStaticMethod{
public static void main(String args[])
{
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan SVREC
222 Aryan SVREC
333 Sonoo SVREC

Static Block
 Java supports a special block, called a static block (also called static clause) that
can be used for static initialization of a class.
 Code inside the static block is executed only once.
 Static block executes automatically when the class is loaded in memory.
Example

class A2
{
static{System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");

}
}
Output:
static block is invoked
Hello main

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor The method is not provided by the compiler in
if you don't have any constructor in a class. any case.

The constructor name must be same as the class The method name may or may not be same as the
name. class name.

**********************
String
 Strings are the type of objects that can store the character of values and in Java.
 A string acts the same as an array of characters.

For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch); ssame as:
Strings="javatpoint";
EXAMPLE:
public class StringExample {
public static void main(String args[])
{
String str = new String("example");
System.out.println(str);
}
}
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang. Stringclass


implements Serializable, Comparable and CharSequence interfaces.

The CharSequence interface is used to represent sequence of characters. It is implemented by String,


StringBuffer and StringBuilder classes. It means, we can create string in java by using these 3
classes.
The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new
instance is created. For mutable string, you can use StringBuffer and StringBuilder classes.

Creating a String
There are two ways to create a string in Java
1. String Literal
2. Using new Keyword
1. String Literal
 No new objects are created if it exists already in the string constant pool
Example:
String demoString = “GeeksforGeeks”;
2. Using new Keyword
 String s = new String(“Welcome”);
 In such a case, JVM will create a new string object in normal (non-pool) memory
String Buffer Class in Java
 StringBuffer is a class in Java that represents a mutable sequence of characters.
 It provides an alternative to the immutable String class, allowing you to modify the
contents of a string without creating a new object every time.
String creates strings of fixed_length
 In stringbuffer class we can insert characters and substrings in the middle of a string, or
append another string to the end
Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with an initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.

Syntax

StringBuffer sb = new StringBuffer();

Example. StringBuffer java

public class StringBufferExample {


public static void main(String[] args) {
// Creating a StringBuffer
StringBuffer sb = new StringBuffer("Hello");
// Appending to the StringBuffer
sb.append(", World!");
// Inserting into the StringBuffer
sb.insert(5, " Java");
// Deleting from the StringBuffer
sb.delete(5, 10);
System.out.println(sb); // Output: Hello, World!
}
}
Output:

Hello, World!

Methods of the StringBuffer class:


StringBuffer class methods

1 public StringBuffer append(String s)


Updates the value of the object that invoked the method. The method takes
boolean, char, int, long, Strings, etc.
2 public StringBuffer reverse()
The method reverses the value of the StringBuffer object that invoked the
method.
3 public delete(int start, int end)
Deletes the string starting from the start index until the end index.
4 public insert(int offset, int i)
This method inserts a string s at the position mentioned by the offset.
5 replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer with
characters in the specified String.

String Class Methods


Method 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 appearances of x with y
;
s1.equal(s2); Returns true if s1 is equal to s2
s2=s1.trim(); Remove white space at the beginning and end of the
String
s1
s1.equalsIgnoreCase Returns true if s1 is equal to s2, ignoring the case of
(
characters
s2);
s1.length(); Gives the length of s1.
s1.charAt(n) Gives nth character of s1
s1.concat(s2); Concatenates s1 and s2
s1.substring(n); Gives substring starting from nth character.
s1.substirng(n,m); Gives substring starting from nth character up to mth
character
String.valueOf(p); Creates a string object of the parameter p(simple
type or
object)
p.toString(); Creates a string representation of object p
s1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’ in the
string s1
s1.indexOf(‘x’,’n’); Gives the position ‘x’ that occurs after nth position in
the
string s1
String.valueOf(variab Converts the parameter value to string
le representation.
);
s1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2, zero if s1
and s2
equal.

STRING STRING BUFFER CLASS


The String class is immutable. The StringBuffer class is mutable.

String is slow and consumes more memory when we


StringBuffer is fast and consumes less memory
concatenate too many strings because every time it
we concatenate t strings.
creates new instance.

String class overrides the equals() method of Object


StringBuffer class doesn't override the equals(
class. So you can compare the contents of two strings
method of Object class.
by equals() method.

String class is slower while performing concatenation StringBuffer class is faster while performing
operation. concatenation operation.

String class uses String constant pool. StringBuffer uses Heap memory

*************************

You might also like