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

Java_CH_1

The document provides an overview of programming paradigms, detailing imperative and declarative paradigms, their types, advantages, and disadvantages. It also covers object-oriented programming concepts such as classes, objects, abstraction, encapsulation, inheritance, and polymorphism, along with a brief history and features of Java, including its compiler, interpreter, and multithreading capabilities. Additionally, it explains the Java Development Kit (JDK) and the role of bytecode and the Java Virtual Machine (JVM).

Uploaded by

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

Java_CH_1

The document provides an overview of programming paradigms, detailing imperative and declarative paradigms, their types, advantages, and disadvantages. It also covers object-oriented programming concepts such as classes, objects, abstraction, encapsulation, inheritance, and polymorphism, along with a brief history and features of Java, including its compiler, interpreter, and multithreading capabilities. Additionally, it explains the Java Development Kit (JDK) and the role of bytecode and the Java Virtual Machine (JVM).

Uploaded by

Makwana Dharmraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

MRK - 9537405667

CH 1
 Introduction to programming paradigm
In layman's terms, programming paradigms are a fundamental style of
computer programming.
In technical terms, a programming paradigm is a way to deal with tackle
issues utilizing some programming language. Additionally, we can say that
it is a strategy to take care of an issue using tools and techniques that are
accessible to us following some methodology.
It differs in the concepts and methods that are used to represent the
elements (such as objects, variables, functions, and constraints) of a
program. And the steps that involve a calculation (like assignations,
evaluation, continuations, and data flows). The lowest programming
paradigm is machine code.
There are lots of things for programming languages that are known.
However, every one of them needs to follow some procedure when they
are executed and this approach/methodology is a paradigm.

Types of Programming Paradigms


There is the following two programming paradigm:
A) Imperative Programming Paradigm
B) Declarative Programming Paradigm

1
A) Imperative Programming Paradigm

Imperative programming is a programming paradigm that uses statements that


change a program's state. An imperative program consists of commands for the
computer to perform. It describes the detail of how the results are to be
obtained. How means describing the inputs and describing how the outputs are
produced.

Examples of imperative programming paradigm are C, Fortran, Basic, Java,


C++, Python, Ruby, PHP, etc.

Advantages
o Easy to implement.
o It contains loops, variables, etc.
o It is efficient.

Disadvantages
o We cannot choose it for solving complex problems.
o It is less efficient and less productive.
o It is not suitable for parallel programming.
o Order is crucial.

 Types of Imperative Programming Paradigm

There are the following types of imperative programming paradigms:

o Object-oriented Programming
o Procedural Programming
o Parallel Processing Approach

Object-oriented Programming

The object-oriented programming paradigm is based on the concept of object.


An object contains data in the form of fields that are known as attributes
and the procedures are known as methods.

Since objects work independently, they are encapsulated into modules. we can
communicate with an object by using message passing.

Object-oriented programming can be achieved by using programming languages


such as Java, C++, C#, PHP, and Python, etc.
2
Procedural Programming

The paradigm deals with procedure calls that are called routines or functions. the
functions contain a series of computational commands to be carried out to
achieve a certain outcome.

It is just like a procedure, with a list of step-by-step instructions for the computer
program to follow. The code can easily be reused in different parts of the
program. The advantage of the paradigm is that the code can be easy to learn and
read in simple programs. Though, while dealing with a complex problem, we run
the risk of ending up with a huge volume of code.

Example of procedural programming is BASIC, C, and Pascal.

Parallel Processing Approach

The parallel programming paradigm breaks the problem or task into chunks that
are distributed among multiple processors. These chunks work on the same
problem, simultaneously. It reduces the total time to solve a problem. It connects
multiple processors to the memory. It is either pooled across all processors or
distributed over a network.

There are several programming languages that support parallel processing.

Example of parallel programming paradigm is SISAL, Parallel Haskell,


SequenceL, System C (for FPGAs), Mitrion-C, VHDL, and Verilog, MPI.

Declarative Programming Paradigm

Declarative programming is a style of building the structure and elements of


computer programs. It expresses the logic of a computation without describing
its control flow. In other words, styles of programming that are not imperative
are called declarative programming paradigm. It emphasizes what the program
should accomplish.

Examples of declarative programming paradigm are Scala, Haskell, Erlang,


Lisp, ML, Closure, SQL, XSQL, etc.

Advantages
o Efficient and shortcode
o Referential Transparency
o Idempotence
o Error recovery
3
o Readability
o Commutativity
o Easy optimization

Disadvantages
o Difficult to understand.
o It is abed on an unfamiliar conceptual model.
o Difficult to accept characteristics of specific applications into account
while programming.

Types of Declarative Programming Paradigms


o Functional Programming
o Logical Programming
o Database Processing Approach

Functional Programming

It is a subset of declarative programming. Programs that are written using the


paradigm use functions, blocks of codes, intended to behave like mathematical
functions. It discourages changes in the value of variables through the
assignment. Instead makes a great deal with recursion.

Examples of functional programming Haskell, SML, Clojure, Scala, Erlang,


Clean, F#, etc.

Logical Programming

The Logical Paradigm adopts a decisive strategy to critical thinking. Different


consistent declarations about a circumstance are made, setting up totally known
realities. The paradigm is divided into three sections:

1. A series of definitions/affirmations that characterize the problem domain


2. Statements of facts that are relevant
3. Statement of objectives or goals in the form of query

Example of logical programming is PROLOG, SQL, etc.

Database Processing Approach

4
The data-driven programming paradigm depends on information and its
development. In this paradigm, the program statements are characterized by data
instead of hard-coding a progression of steps. A data set program is the core of a
business data framework and gives document creation, information section,
update, query, and reporting functions.

There are a few programming dialects that are developed for the most part for
data set applications. For example, SQL. It is applied to surges of organized
information, for filtering, transforming, aggregating, or calling different projects.
So, it has its own wide application.

Example of database processing approach programming is SQL (only DQL),


QML, RDQL, and SPARQL.

Apart from the imperative and declarative programming approach, there is


another paradigm that is known as the multi-paradigm.

Multi-Paradigm

The programming languages that support more than one programming


paradigm fall into this category. The design goal of such languages is to allow
programmers to use the most suitable programming style associated with
languages constructs for a given job.

The example of multi-paradigm programming languages is C++, Java, Python,


etc. The languages support object-oriented programming greater or lesser degree,
typically in combination with imperative and declarative programming
paradigm.

Usually, in a program, distinctive programming standards are utilized.


Henceforth, programming dialects offer help (with various degrees) for the
different standards.

5
 Imperative Vs. Declarative Programming Paradigm
Basis of Imperative Paradigm Declarative Paradigm
Comparison

Programming Its style is step by step. Define what the problem is and
Style what data transformations are
needed.

Approach It follows It follows a non-


a traditional approach. traditional approach.

Programmer It describes how to solve It describes what the problem


Focuses problems. is.

Decision The user makes decisions and It allows the compiler to make
Capability instructs the compiler. decisions.

Consist of It is a sequence It is a set of statements.


of commands.

Flow It expresses control flow. It expresses data flow.

State Change It is important. It does not exist.

Primary Instances of classes and Functions as first-class object


Manipulation structure. and data collections.
Unit

Order of Order of execution Order of execution is not


execution is important. important.

Example C, FORTRAN, Ada, Python, PROLOG, LISP, Haskell, ASP,


etc. etc.

6
 Basic Of OOP :-
1) What is Class ?

A class in Java is a logical template to create objects that share common


properties and methods. Hence, all objects in a given class will have the same
methods or properties. For example: in the real world, a specific cat is an
object of the “cats” class. A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

7
class <class_name>{
field;
method;
}
2) What is Object ? :-

An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). The example of an intangible object is the banking system.
For Example, Pen is an object. Its name is Reynolds; color is white, known as
its state. It is used to write, so writing is its behavior.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

3) Abstraction :-

Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or
interfaces.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details. The
properties and behaviors of an object differentiate it from other objects of
similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of a car or applying brakes
will stop the car, but he does not know how on pressing the accelerator the
speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of the accelerator, brakes, etc in the car.
4) Encapsulation

Encapsulation in Java is a process of wrapping code and data together into a


single unit, for example, a capsule which is mixed of several medicines.

8
We can create a fully encapsulated class in Java by making all the data members
of the class private. Now we can use setter and getter methods to set and get the
data in it.

5) Inheritance

Inheritance in Java is a concept that acquires the properties from one class to
other classes; for example, the relationship between father and son. Inheritance
in Java is a process of acquiring all the behaviours of a parent object.
The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Advantages of Inheritance

Minimizing duplicate code: Key benefits of Inheritance include minimizing the


identical code as it allows sharing of the common code among other subclasses.

Flexibility: Inheritance makes the code flexible to change, as you will adjust
only in one place, and the rest of the code will work smoothly.

Overriding: With the help of Inheritance, you can override the methods of the
base class.

Data Hiding: The base class in Inheritance decides which data to be kept
private, such that the derived class will not be able to alter it.

6) What is Polymorphism

polymorphism in Java is a concept by which we can perform a single action in


different ways. Polymorphism is derived from 2 Greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
9
There are two types of polymorphism in Java: compile-time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.

If you overload a static method in Java, it is the example of compile time


polymorphism.

Histroy Introduction & Language


 History of Java
• Java is General purpose object oriented Programming Language.
Developed by Sun Microsystems of U.S.A

• Mr. James Gosling one Of the Developer of the Language “OAK’.

• initially java was Develop for Making the software for consumer
Electronic Devices like TV, microwave(sensor technology)

• The Developer team has reviewed the existing Language like c and
c++ and combine the advantage of both language and remove
the limitation and then develop the simple ,reliable ,portable
and power tool language that is called Java as we can show in
below figure

 Explain java features


1. Compiler and interpreter
• Usually any programming language will be either compiler or
interpreter but java has combine both the approaches

10
• so become two stage system in it first stage java compiler
translate source code to machine independent byte code in the
second stage java interpreter will run this byte code in the
destination machine.
• Compiler: - C, C++, VB, FOXPRO….
• Interpreter: - Scripting language, HTML, PHP

2.Platform independent
• This is the most important and power full future of JAVA
program can run anyway any time changes on upgrade in
operation system or any other system recourses will not affect the
JAVA program to run.
• This is the reason why JAVA become most popular language on
the internet because on internet each and every pc will have
different configuration.

3. Object oriented
• Java is pure object oriented programming and that’s while
everything in java is an object
4.Secure and robust
• When we have a language for internet base programming security
is the first and for most issues security in the sense of protection
from wireless or security of data
• Java does not support * pointer so direct access of memory will
not allow and that why ever program and data will become secure
and robust
5. Distributed
• JAVA programming language has the ability to run program on
distributed network so that it allow us that multiple location can
develop a single project
6.Simple, small & familiar

11
• JAVA is simple language because all the feature like if condition
,for loop ,while loop , switch case, and so on of the most popular
language like C,C++
• JAVA is small language because it consists of only six packages.
The package is same feature combination of C and C++ which we
can familiar this language.

7. Dynamic
• JAVA is dynamic language because one can add new feature all
new feature all new classes.
• To the java itself we can also call it as extension language which
can be extend whenever needed.
8.Multithreading
• Multithreading meaning handling of multiple task at a time.
• Java supports multithreaded programming this means that we
does not have to wait for a process to complete instead of that we
can start new process while the current process running.
9.High performance
• When you develop at require very much less memory as well as
high speed that’s while its give us high performance.
 What is JDK?
The Java Development Kit (JDK) is an implementation of either one of the Java
SE, Java EE or Java ME platforms released by Oracle Corporation in the form of a
binary product aimed at Java developers on Solaris, Linux, Mac OS X or Windows.
JDK Tool Meaning Use

Javac Java Compiler Compiles the source code (.java file) &
translates it into Bytecode.

Java Java Interpreter Interprets Bytecode & generates output.


Javadoc Java Used to create documentation for java source

Documentation code in HTML format.

12
Javah Java Header It produces header files for the program

files which uses native methods. This file is


included in your program which calls this
native method

Javap Java It converts Bytecode file (.class file) to

disassemble program description

Jdb Java debugger Used to debug your program

applerviewer Applet Viewer Used to execute java Applets.

 Bytecode & JVM Machine


• With most programming languages, you either compile or
interpret a program so that you can run it on your computer.

• The Java programming language is unusual in that a program is


both compiled and interpreted.

• With the compiler, first you translate a program into an


intermediate language called Java

• The platform-independent codes interpreted by the interpreter on


the Java platform.

• The interpreter parses and runs each Java instruction on the


computer.

• Compilation happens just once; interpretation occurs each time


the program is executed.
• The following figure illustrates how this works.

13
• You can think of Java bytecodes as the machine code instructions
for the Java Virtual Machine (JVM).
• Every Java interpreter, whether it's a development tool or a Web
browser that can run applets, is an implementation of the JVM.

• Java byte codes help make "write once, run anywhere" possible.

• You can compile your program into bytecodes on any platform


that has a Java compiler.

• The byte codes can then be run on any implementation of the


JVM.

• That means that as long as a computer has a JVM, the same


program written in the Java programming language can run on
Windows 2000, a Solaris workstation, or on an iMac.

14
 Java Runtime Environment (JRE)
 The Java Runtime Environment (JRE), also known as Java
Runtime,

 The Java Development Kit (JDK), a set of programming tools for


developing Java applications.

 The Java Runtime Environment provides the minimum


requirements for executing a Java application;

 it consists of the Java Virtual Machine (JVM), core classes, and


supporting files.

 Compiling & Executing basic java program


Step1:
Open the Windows Command prompt and type this command .Here we
are opening notepad with the filename Class1.java (Please remember
the .java extension)

Steps for compiling and running your first java program using the
Java Development kit from Sun Microsystems

Step2:

15
Notepad would ask if you want to create the file. Click on Yes. This
would create the file and you can type the code in it

Step3:
Type the following code. All this code does is print Hello World! on the
screen. Remember Java is case sensitive

class a1
{
public static void main(String[] args){
System.out.println("Hello RPBC");
}
}

Step4:
Compilation Now Save the file and get back to the command prompt
and type the following command as shown.

javac a1.java
This command would compile a1.java and produce a1.class which
contains Java byte code which is machine independent.

Step5:
Running the program If you have any errors, you would see them on
the screen.

java a1
Please go back to notepad and correct the errors and resave the file.
If you see a blank output after the javac command,
it means there were no errors and you are ready to run the program.
You could run the program using the command as shown in the
screen shot.

Hello RPBC

16
Data Type in Java
Data Type Range Size
(Byte)
Byte -128 to 127 1
Short -32768 to 32767 2
Int -2147483648 to 4
2147483647
Long -9223372036854775808 to 8
9223372036854775807
Float 3.4*10-38 to 3.438 4
Double 1.7*10-308 to 1.7*10+308 8
Char Single character 2
Boolean Either true or false 1

 Explain the Structure of java OR

Question : Explain the following line in JAVA

public static void main(String args[])

Answer :
class xyz
{
public static void main (String args [])
{
System.out.println (“hello”);
}
}

17
In above example we can see xyz is a class name and the description of
public static void main (String args []) as we can see bellow.

public:-
The public keyword is access specified which means that the
contain of the following block accessible from all other classes.

static:-
The keyword static allow main to be called without having
instance of class (duplication copy of object).

void:-
The keyword void tell to the compiler that main () does not return
value.

main ()

main () is method called when Java application begin Java is


case sensitive main is different from MAIN Java compiler will compile
classes that doesn’t contain a main method but Java has no may to
run is classes.

String args []
Declare a parameter name which is an array of instance
of the class string args receive and command line argument precision
when the program is executed.

System.out.println()
System is predefining classes that provide access to the system.
Out is the output stream that is connecting to the console.
Output is a complies by the build in println method.

 Explain Basic Structure of Java program.


Basic structure of a Java program is as under.
1. Documentation section
2. Package statement
3. Import statement
4. Class definition
5. Main method

18
1. Documentation section
In this section you can write the documentation for your program
like, program definition, author information, the logic of your
program etc. this is optional section.
It is written in comment lines (//) or (/* …………..*/)

2. Package statement
If you want to save your program in a package(directory) then the
package statement is included. This is also an optional section.

3. Import statement
If you want to import any library or user-defined package, the
import statement is used. Now from this imported package, you
can use its classes & methods. This is also an optional section.

Ex : import java.util.Date;

4. Class Definition
You can define classes in this section. Use class keyword to
declare a class. There can be member variable & methods in this
class. This is required & its compulsory section.

5. Main method
In your program, you can more than one class, but there should
be one class that contains the main method.
This class is run to generate output because the main method is
the entry point for program execution. This is compulsory
section.

19
Java Tokens
 Comments
There are three types of comment in java.
1. Single line comments : Double slashes are used to indicate single line
comment.
Ex. //This is a single line comment.
2. Multi-line comments :
The text written between /* and */ are considered comments.
Ex : /*
This is documentation comment
Rpbc
*/

 Operator in Java
Operators
In java language there are same operators which we was used in the C and C++.
There are
Arithmetic Operators
Arithmetic operators are used in mathematical expression in the same way that
they are used in algebra. The following table lists the arithmetic operators:
Operator Result
+ Addition
- Subtraction(also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition Assignment
-= Subtraction Assignment
/= Division Assignment
%= Modulus Assignment
*/ Multiplication Assignment
-- Decrement

The Modulus Operators


The modulus operation, % returns the remainder of a division operation. It can
be applied to floating-point types as well as integer types. The following
example program demonstrates the %:

20
In Arithmetic Assignment Operators
Java provides special operators that can be used to combine an arithmetic
operation with an assignment. As you probably know, statements like the
following are quite common in programming.
a = a + 4;

In java, you can rewrite this statement as shown here;


a+=4;

This version uses the += compound assignment operator. Both statements


perform the same operation: they increase the value of a by 4. Another example:
a = a / 4; a /= 4;
a = a % 4; a %= 4;
a = a - 4; a -= 4;

The compound assignment operator provides two benefits. First, they save you a
bit of typing, because they are “shorthand” for their equivalent long forms.
Second, they are implemented more efficiently by the java run-time system than
are their equivalent long forms. For these reasons, you will often see the
compound assignment operators used in professionally written java programs.
Increment and Decrement Operators
The ++ and -- are Java’s increment and decrement operators.
The ++ (Increment Operators) increase its operand by one.
The -- (decrement Operators) decrease its operand by one. For example, this
statement.
x = x + 1; x = x – 1;
can be rewritten like this by use of the
x++; ++x; x--; --x;

These operators are unique in that they can appear in prefix (++x) and postfix
(x++) form. For example:-
The Bitwise Operators
Bitwise and bit shift operators are used on integral types (byte, short, int and
long) to perform bit-level operations.
Java Bitwise and Bit Shift Operators
Operator Description
| Bitwise OR
& Bitwise AND
~ Bitwise Complement
^ Bitwise XOR
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
21
Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
The | operator compares corresponding bits of two operands. If either of the bits
is 1, it gives 1. If not, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
The & operator compares corresponding bits of two operands. If both bits are 1,
it gives 1. If either of the bits is not 1, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It is
denoted by ~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.
35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

Why are we getting output -36 instead of 220?

It's because the compiler is showing 2's complement of that number; negative
notation of the binary number.

22
Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.
The ^ operator compares corresponding bits of two operands. If corresponding
bits are different, it gives 1. If corresponding bits are same, it gives 0. For
example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
| 00011001
________
00010101 = 21 (In decimal)

The Left Shift


The left shift operator << shifts a bit pattern to the left by certain number of
specified bits, and zero bits are shifted into the low-order positions.
212 (In binary: 11010100)

212 << 1 evaluates to 424 (In binary: 110101000)


212 << 0 evaluates to 212 (In binary: 11010100)
212 << 4 evaluates to 3392 (In binary: 110101000000)

The Right Shift


The right shift operator >> shifts a bit pattern to the right by certain number of
specified bits.
212 (In binary: 11010100)

212 >> 1 evaluates to 106 (In binary: 01101010)


212 >> 0 evaluates to 212 (In binary: 11010100)
212 >> 8 evaluates to 0 (In binary: 00000000)

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

int number = 212, result;

System.out.println(number >> 1);


System.out.println(number >> 0);
System.out.println(number >> 8);
}
}
23
Relational Operators

The relational Operators determine the relationship that one operand has to
another. Specifically, they determine equality and ordering. The relational
operators are shown here.
Operator Result
== Equal to
!= Not Equal to
> Greater than
< Less than
>= Greater than or Equal to
<= Less than or Equal to

The relational operators have always BOOLEAN value either true or false.
These operators are use in control statement line IF condition and loop. It is
same as C and C++.

 Type Casting in Java

Java supports two types of castings – primitive data type casting


and reference type casting.

Reference type casting is nothing but assigning one Java object to


another object.

It comes with very strict rules and is explained clearly in Object


Casting.

Java data type casting comes with 2 flavors.

1. Implicit casting
2. Explicit casting

1. Implicit casting (widening conversion)

A data type of lower size (occupying less memory) is assigned to a


data type of higher size.

This is done implicitly by the JVM. The lower size is widened to higher
size. This is also named as automatic type conversion.

Examples:

24
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0

In the above code 4 bytes integer value is assigned to 8 bytes double


value.

byte –> short –> int –> long –> float –> double
2. Explicit casting (narrowing conversion)

A data type of higher size (occupying more memory) cannot be


assigned to a data type of lower size.

This is not done implicitly by the JVM and requires explicit casting; a
casting operation to be performed by the programmer.

The higher size is narrowed to lower size.

double x = 10.5; // 8 bytes

int y = x; // 4 bytes ; raises compilation error

In the above code, 8 bytes double value is narrowed to 4 bytes int


value. It raises error. Let us explicitly type cast it.

double x = 10.5;
int y = (int) x;

The double x is explicitly converted to int y. The thumb rule is, on


both sides, the same data type should exist.

In the above statement, left to right can be assigned implicitly and


right to left requires explicit casting.

That is, byte can be assigned to short implicitly but short to byte
requires explicit casting.

Following char operations are possible.

25
public class Demo

public static void main(String args[]) {

char ch1 = 'A';

double d1 = ch1;

System.out.println(d1); // prints 65.0

System.out.println(ch1 * ch1); // prints 4225 , 65 * 65

double d2 = 66.0;

char ch2 = (char) d2;

System.out.println(ch2); // prints B }

 Decision Statements

The decision statements also known as selection statements in java. There are
two decision statements are if and switch.
if statements:-
If statements in Java are used to control the program flow based on some
condition, it’s used to execute some statement code block if expression is
evaluated to true, otherwise it will get skipped. This is a simplest way to modify
the control flow of the program.

Syntex:-
if(condition)
{
Statement;
}

Nested ifs:-
A nested if is a statement that is the target of another if or else. Nested if are very
commonly in programming. When you nest ifs, the main thing to remember is
that an else statement always refers to the nearest if statement that is within the
same block as the else not already associated with an else. Example:-
if(i == 100)
{
if(j < 20) a=b;
26
if(k > 100) c=d;
else a =c;
}
else
a = d;

The if-else-if Ladder:-


A common programming construct that I based upon a sequence of nested ifs is
the if-else-if ladder. It look like this:

if(condition)
statements;

else if(condition)
statements;

else if(condition)
statements;
.
.
.
else
statement;

Switch..case
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked
for each case.
Syntax
switch(expression) {
case value :
// Statements
break; // optional

case value :
// Statements
break; // optional

// You can have any number of case statements.


default : // Optional
// Statements
}
The following rules apply to a switch statement −
27
 The variable used in a switch statement can only be integers, convertable
integers (byte, short, char), strings.
 You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the
switch and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.

 Looping Statement

There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general form of a loop statement in most of
the programming languages
Java programming language provides the following types of loop to handle
looping requirements. Click the following links to check their detail.
Sr.No. Loop & Description

while loop
1 Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.

for loop
2 Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

do...while loop
3 Like a while statement, except that it tests the condition at the end of the loop
body.

28
While loop:-
A while loop statement in Java programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax
The syntax of a while loop is −

while(Boolean_expression) {
// Statements
}
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non zero value.

When executing, if the boolean_expression result is true, then the actions inside
the loop will be executed. This will continue as long as the expression result is
true.
When the condition becomes false, program control passes to the line
immediately following the loop.

for loop;-
A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax
The syntax of a for loop is −
for(initialization; Boolean_expression; update) {
// Statements
}
Here is the flow of control in a for loop −
 The initialization step is executed first, and only once. This step allows
you to declare and initialize any loop control variables and this step ends
with a semi colon (;).
 Next, the Boolean expression is evaluated. If it is true, the body of the loop
is executed. If it is false, the body of the loop will not be executed and
control jumps to the next statement past the for loop.
 After the body of the for loop gets executed, the control jumps back up to
the update statement. This statement allows you to update any loop control
variables. This statement can be left blank with a semicolon at the end.
 The Boolean expression is now evaluated again. If it is true, the loop
executes and the process repeats (body of loop, then update step, then
Boolean expression). After the Boolean expression is false, the for loop
terminates.

29
For-each loop (Advanced or Enhanced For loop):
As of Java 5, the enhanced for loop was introduced. This is mainly used to
traverse collection of elements including arrays. The advantage of for-each loop
is that it eliminates the possibility of bugs and makes the code more readable.
Syntax
Following is the syntax of enhanced for loop −
for(declaration : expression) {
// Statements
}
 Declaration − The newly declared block variable, is of a type compatible
with the elements of the array you are accessing. The variable will be
available within the for block and its value would be the same as the
current array element.
 Expression − This evaluates to the array you need to loop through. The
expression can be an array variable or method call that returns an array.
class For1
{
public static void main(String a[])
{
int numbers[]={10,20,30,40,50};
for(int x : numbers)
{
if(x==30)
break;
System.out.println(x);

}
}
}
do…while Loop;-
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax
Following is the syntax of a do...while loop −
do {
// Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the
statements in the loop execute once before the Boolean is tested.

30
If the Boolean expression is true, the control jumps back up to do statement, and
the statements in the loop execute again. This process repeats until the Boolean
expression is false.

 Jumping Statement

Break:-
The break statement in Java programming language has the following two
usages −
 When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
 It can be used to terminate a case in the switch statement (covered in the
next chapter).
Syntax
The syntax of a break is a single statement inside any loop −
break;
continue:-
The continue keyword can be used in any of the loop control structures. It causes
the loop to immediately jump to the next iteration of the loop.
 In a for loop, the continue keyword causes control to immediately jump to
the update statement.
 In a while loop or do/while loop, control immediately jumps to the
Boolean expression.
Syntax
The syntax of a continue is a single statement inside any loop −
continue

Array
An array stores a group of data items all of the same type.

Declare an array variable by specifying the type of data to be stored,


followed by square brackets [].

dataType[] variableName;

Instantiating Arrays
Instantiate an array object using new, the data type, and an array size
in square brackets

int[] nums;
nums = new int[10];

31
The second line constructs a new array object with 10 integer
elements, all initialized to 0, and stores the reference into nums.

int[] moreNums;
int size = 7;
moreNums = new int[size];

You can declare and instantiate all at once:

String[] names = new String[3];

The elements of the array, String references, are initialized to null.

As objects, arrays also have a useful property: length:

 In the above example, names.length would be 3.


 The property is fixed (i.e., it is read-only).

You can reassign a new array to an existing variable:

int[] nums;
nums = new int[10];
nums = new int[20];

The original ten-element array is no longer referenced by nums, since


it now points to the new, larger array.

Initializing Arrays
An array can be initialized when it is created

The notation looks like this:

String[] names = { "hello", "rpbc", "student" };

or
32
String[] names = new String[]{ "hello", "rpbc", "student" };

This automatically creates an array of length 3, because there were 3


items supplied.

int[] nums = new int[] { 2, 4, 6, 8, 10, 12 };

This array will have a length of 6.

If a new array is being assigned to an existing variable,

Two Dimensional Array [Rectangular Array]

Java doenot truely support multidimensional arrays.


In java ,a two dimensional array is simply an array of arrays,

We can see in bellow example

int x = 5;
int y = 5;

String[][] arr1 = new String [x][y];

arr1[0][x] = "hello";
arr1[0][y] = "rpbc";

Command –line arguments

You can pass argument to the main() method. This can be done at
runtime.

As we know that the main() method takes array of string as argument,


the arguments given to the main() method will be assigned to this
array.

Thus giving commands-line argument is quite easy in java.

Following program shows how to give & receive command-line


arguments in a program.

class test1

33
public static void main(String args[]) {

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

System.out.println(“argument are :”+i+ “ :”+args[i]);

How to run program

 javac test1.java
 java test1 hi hello bye

output

Argument 0: hi

Argument 1: hello

Argument 2: bye

Command Line Argument Array


 Sometimes you will want to pass information into a program when you run
it.
 This is accomplished by passing COMMAND-LINE ARGUMENTS TO
MAIN().
 A commang0line argument is the information that directly follows the
program’s name on the command line when it is executed.
 To access the command-line argument inside a java program is quite easy
they are stored as strings in a String array passed to the args parameter of
main().
 The first command-line argument is stored at args[0], the second at
args[1], and so on.
Garbage Collection :-
In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory


automatically. In other words, it is a way to destroy the unused objects.

34
To do so, we were using free() function in C language and delete() in C++. But,
in java it is performed automatically. So, java provides better memory
management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.

How can an object be unreferenced?


o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.

1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

35

You might also like