0% found this document useful (0 votes)
4 views87 pages

Java 1st Unit Notes

The document outlines the course on Object Oriented Programming with Java, covering key concepts such as the differences between system and application software, procedural and object-oriented programming paradigms, and comparisons between C++ and Java. It also introduces Java as a widely used programming language, detailing its features, primitive types, and the principles of object-oriented programming. The document serves as a comprehensive guide for understanding Java fundamentals and its applications.

Uploaded by

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

Java 1st Unit Notes

The document outlines the course on Object Oriented Programming with Java, covering key concepts such as the differences between system and application software, procedural and object-oriented programming paradigms, and comparisons between C++ and Java. It also introduces Java as a widely used programming language, detailing its features, primitive types, and the principles of object-oriented programming. The document serves as a comprehensive guide for understanding Java fundamentals and its applications.

Uploaded by

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

Course Title: Object Oriented Programming with Java

Course Code: B22EF0302

UNIT-1
OOPS CONCEPTS & JAVA FUNDAMENTALS

**Differences between System & Application Software

System Software Application Software

The Software that is designed to control, integrate A set of computer programs installed in the
and manage the individual hardware components user’s system and designed to perform a
and application software is known as system specific task is known as application
software. software.

System Software maintains the system resources Application software is built for specific
and gives the path for application software to run. tasks.

Low-level languages are used to write the system While high-level languages are used to write
software. the application software.

It is general-purpose software. While it’s a specific purpose software.

Without system software, the system stops and While Without application software system
can’t run. always runs.

System software runs when the system is turned While application software runs as per the
on and stops when the system is turned off. user’s request.

Example: System software is an operating system, Example: Application software is


System Software Application Software

etc. Photoshop, VLC player, etc.

System Software programming is more complex Application software programming is


than application software. simpler in comparison to system software.

A system software operates the system in the Application software runs in the front end
background until the shutdown of the computer. according to the user’s request.

The system software has no interaction with Application software connects an


users. It serves as an interface between hardware intermediary between the user and the
and the end user. computer.

Application software is dependent on system


System software runs independently. software because they need a set platform
for its functioning.

Example for System Software includes Android, Examples of Application Software includes
Mac Operating system, MS Windows, Compiler, MS Word, MS Power Point, Adobe Reader,
Assembler, loader etc. VLC Player, games, etc.

**Differences between Procedure Oriented & Object-


Oriented Programming Paradigm

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is In object-oriented programming, the program is


divided into small parts called functions. divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows


Procedural Oriented Programming Object-Oriented Programming

approach. a bottom-up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.

In procedural programming, overloading is not Overloading is possible in object-oriented


possible. programming.

In procedural programming, there is no concept In object-oriented programming, the concept of


of data hiding and inheritance. data hiding and inheritance is used.

In procedural programming, the function is In object-oriented programming, data is more


more important than the data. important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for designing Object-oriented programming is used for


medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the concept
procedure abstraction. of data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.
Procedural Oriented Programming Object-Oriented Programming

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

**Differences between C++ and Java

Parameters Java C++

Platform Platform-independent, Java bytecode Platform dependent should be


Dependency works on any operating system. compiled for different platforms.

It can run on any OS hence it is C++ is platform-dependent.


Portability portable. Hence it is not portable.

Java is both a Compiled and Interpreted


C++ is a Compiled Language.
Compilation Language.

Memory Memory Management is System Memory Management in C++ is


Management Controlled. Manual.

Virtual Keyword It doesn’t have Virtual keywords. It has Virtual keywords.

It supports only single inheritance.


It supports both single and
Multiple Multiple inheritances are achieved
multiple Inheritance.
Inheritance partially using interfaces.

It supports only method overloading It supports both method and


Overloading and doesn’t allow operator overloading. operator overloading.
Parameters Java C++

Pointers It has limited support for pointers. It strongly supports pointers.

It supports direct system library


It doesn’t support direct native library
calls, making it suitable for
calls but only Java Native Interfaces.
Libraries system-level programming.

Libraries have a wide range of classes C++ libraries have comparatively


Libraries for various high-level services. low-level functionalities.

Documentation It supports documentation comments It doesn’t support documentation


Comment (e.g., /**.. */) for source code. comments for source code.

C++ doesn’t have built-in support


Java provides built-in support for
for threads, depends on third-
multithreading.
Thread Support party threading libraries.

C++ is both a procedural and an


Java is only an object-oriented
object-oriented programming
programming language.
Type language.

Java uses the (System


C++ uses cin for input
Input-Output class): [Link] for input
and cout for output operation.
mechanism and [Link] for output.

goto Keyword Java doesn’t support the goto Keyword C++ supports the goto keyword.

Structures and Java doesn’t support Structures and C++ supports Structures and
Unions Unions. Unions.

Parameter Java supports only the Pass by Value C++ supports both Pass by Value
Passing technique. and pass-by-reference.
Parameters Java C++

It supports both global scope and


It supports no global scope.
Global Scope namespace scope.

It supports manual object


Automatic object management with
Object management using new and
garbage collection.
Management deletes.

Hardware Java is not so interactive with hardware. C++ is nearer to hardware.

**Introduction to Java Programming Language


 Java is one of the world’s most important and widely used
computer languages. Java leapt to the forefront of internet
programming with its first release. Today, it is still the first and
best choice for developing web-based applications.
 Java is related to C++, which is a direct descendant of C. Much
of the character of java is inherited from these 2 languages.
From C, java derives its syntax. Many of Java’s object-oriented
features were influenced by C++.
 C is procedure-oriented programming language developed by
Dennis Ritchie in the year 1972 at Bell Labs.
 C++ is object-oriented programming language developed by
Bjarne Stroustrup in the year 1979 at Bell Labs.
 Java is general-purpose object-oriented programming language
developed by James Gosling, Mike Sheriden and Patrick
Naughton in the year 1991 at Sun Microsystems. The Language
was initially called as “Oak” but was renamed “Java” in 1995.
 The primary motivation of java language invention was the
need for a platform-independent (architecture neutral)
language that could be used to create software to be
embedded in various consumer electronic devices, such as
microwave ovens and remote controls. The second force that
made java very famous was it was used for developing web-
based applications (World Wide Web).
 Java provided security or protection by confining an applet to
the java execution environment and not allowing it access to
other parts of the computer. An applet is a special kind of Java
program that is designed to be transmitted over the Internet and
automatically executed by a Java-compatible web browser. The
ability to download applets with confidence that no harm will be
done, and that no security will be breached is considered by
many to be the single most innovative aspect of Java.
 The key that allows Java to solve both the security and the
portability problems is that the output of a Java compiler is not
executable code. Rather, it is bytecode. Bytecode is a highly
optimized set of instructions designed to be executed by the Java
run-time system, which is called the Java Virtual Machine
(JVM). In essence, the original JVM was designed as an
interpreter for bytecode.
 As useful as applets can be, they are just one half of the
client/server equation. Not long after the initial release of Java,
it became obvious that Java would also be useful on the server
side. The result was the servlet. A servlet is a small program that
executes on the server. Just as applets dynamically extend the
functionality of a web browser, servlets dynamically extend the
functionality of a web server. Thus, with the advent of the
servlet, Java spanned both sides of the client/server connection.

**Features of JAVA (JAVA Buzzwords)

1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language because:

* Java syntax is based on C++ (so easier for programmers to learn it


after C++).
* Java has removed many complicated and rarely-used features, for
example, explicit pointers, operator overloading, etc.
* There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.

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.

Object-oriented programming (OOPs) is a methodology that


simplifies software development and maintenance by providing some
rules.

Basic concepts of OOPs are:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

3. Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform specific
machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program
runs.

There are two types of platforms software-based and hardware-based.


Java provides a software-based platform.

The Java platform differs from most other platforms in the sense that
it is a software-based platform that runs on top of other hardware-
based platforms. It has two components:

a. Runtime Environment
b. API(Application Programming Interface)

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, i.e., Write Once and Run Anywhere (WORA).

4. Secured
Java is best known for its security. With Java, we can develop virus-
free systems. Java is secured because:

* No explicit pointer
* Java Programs run inside a virtual machine sandbox

-> Classloader: Classloader in Java is a part of the Java Runtime


Environment (JRE) which is used to load Java classes into the Java
Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are
imported from network sources.

-> Bytecode Verifier: It checks the code fragments for illegal code
that can violate access rights to objects.

-> Security Manager: It determines what resources a class can access


such as reading and writing to the local disk.

Java language provides these securities by default. Some security can


also be provided by an application developer explicitly through SSL,
JAAS, Cryptography, etc.

5. Robust
The English mining of Robust is strong. Java is robust because:

-> It uses strong memory management.


-> There is a lack of pointers that avoids security problems.
-> Java provides automatic garbage collection which runs on the Java
Virtual Machine to get rid of objects which are not being used by a
Java application anymore.
-> There are exception handling and the type checking mechanism in
Java. All these points make Java robust.

6. Architecture-neutral
Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-


bit architecture and 4 bytes of memory for 64-bit architecture.
However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
7. Portable
Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn't require any implementation.

8. High-performance
Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code. It is still a
little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages,
e.g., C, C++, etc.

9. Distributed
Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed
applications. This feature of Java makes us able to access files by
calling the methods from any machine on the internet.

10. Multi-threaded
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. The main advantage of multi-threading is that it
doesn't occupy memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web applications, etc.

11. Dynamic
Java is a dynamic language. It supports the dynamic loading of
classes. It means classes are loaded on demand. It also supports
functions from its native languages, i.e., C and C++

Java supports dynamic compilation and automatic memory


management (garbage collection).
**Primitive Types

Even though Java is an object-oriented programming language, not all


Java values are objects. Instead, some values belong to primitive
types. Four of these types are signed integer types, two are floating-
point number types, one is the character type char that is used in the
encoding for strings, and one is the boolean type for truth values.

Signed Integer types


The signed integer types are for numbers without fractional parts.
Negative values are allowed
Type Storage Range (inclusive)
Requirement
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to
2.147,483,647 (just over 2
billion)
long 8 bytes -
9,223,372,036,854,775,808
to
9,223,372,036,854,775,807

 In most situations, the int type is the most practical. If you


want to represent the number of inhabitants of our planet,
you’ll need to resort to a long. The byte and short types are
mainly intended for specialized applications, such as low-
level file handling, or for large arrays when storage space is
at a premium. In Java, the ranges of the integer types do not
depend on the machine on which you will be running your
program.
 You write long integer literals with a suffix L. There is no syntax
for literals of type byte or short. Use the cast notation, for
example, (byte) 127. Hexadecimal literals have a prefix 0x .
Binary values have a prefix 0b. For example, 0b1001 is 9.

Floating-Point types
The floating-point types denote numbers with fractional parts.
Type Storage Range
Requirement
float 4 bytes Approximately +-
3.4028347E+38F (6-7
significant decimal digits)
double 8 bytes Approximately +-
1.79769313486231570E+308(15
significant decimal digits)

 Many years ago, when memory was a scarce resource,


four-byte floating-point numbers were in common use. But
seven decimal digits don't go very far, and nowadays,
“double precision” numbers are the default. It only makes
sense to use float when you need to store a large number of
them.
 Numbers of type float have a suffix F (for example, 3.14F).
Floating-point literals without an F suffix (such as 3.14)
have type double. You can optionally supply the D suffix
(for example, 3.14D).

The char type


 The char type describes “code units” in the UTF-16
(Unicode Transformation Format-16) character encoding
used by Java. Occasionally, you may encounter character
literals, enclosed in single quotes. For example, 'J' is a
character literal with ASCII value 74.
 The special codes '\n', '\r', '\t', '\b' denote a line feed, carriage
return, tab, and backspace. Use a backslash to escape a single
quote '\'' and a backslash '\\'.
 In old languages like C and C++ we can use only ASCII
characters and to represent all ASCII characters 8-bits are
enough. Hence char size is 1 byte. But in Java we can use
Unicode characters which covers world wide all alphabets
sets. The number of Unicode characters is greater than 256
and hence 1 byte is not enough to represent all characters.
Hence we should go for 2 bytes.
 Unicode characters are prefixed with \u and can be expressed
as hexadecimal values that run from \u0000 to \uFFFF.

Booleans

Java has a primitive type, called boolean, for logical values. It


can have only one of two possible values, true or false. This is
the type returned by all relational operators, as in the case of a <
b. boolean is also the type required by the conditional
expressions that govern the control statements such as if and
for. Size of boolean is 1-bit.

**Variables

Variable Declarations
Java is a strongly typed language. Each variable can only hold
values of a specific type.
Following is the general form of a variable declaration:
type var-name;
Here, type specifies the type of variable being declared, and var-name
is the name of the variable. If you want to declare more than one
variable of the specified type, you may use a comma-separated list of
variable names. When you declare a variable, you need to specify the
type, the name, and an optional initial value.
For example,
int total = 0;
 You can declare multiple variables of the same type in a
single statement:
int total = 0, count; // count is an uninitialized integer
 Most Java programmers prefer to use separate
declarations for each variable. The name of a variable (as
well as a method or class) must begin with a letter. It can
consist of any letters, digits, and the symbols _ and $.
However, the $ symbol is intended for automatically
generated names, and you should not use it in your
names. Finally, the _ by itself is not a valid variable
name.
 You cannot use spaces or symbols in a name. Finally,
you cannot use a keyword such as double as a name.
 By convention, names of variables and methods start
with a lowercase letter, and names of classes start with
an uppercase letter. Java programmers like “camel
case,” where uppercase letters are used when names
consist of multiple words, like CountOfInvalidInputs.

**Variable Initialization
 When you declare a variable in a method, you must
initialize it before you can use it. For example, the following
code results in a compile-time error:

int count;
count++; // Error—uses an uninitialized variable
 The compiler must be able to verify that a variable has been
initialized before it has been used. The variable is declared
at the point at which its initial value is available.

Constants
 The final keyword denotes a value that cannot be changed
once it has been assigned. In other languages, one would
call such a value a constant. For example,

final int DAYS_PER_WEEK = 7;


By convention, uppercase letters are used for names of
constants.
 You can also declare a constant outside a method, using the
static keyword:

public class Calendar


{
public static final int DAYS_PER_WEEK = 7;
...
}
Then the constant can be used in multiple methods. Inside
Calendar, you refer to the constant as
DAYS_PER_WEEK. To use the constant in another class,
prepend the class name: Calendar.DAYS_PER_WEEK.

Structure of Java Program:

Documentation or Comment Section


package statement
import statement
class definition
main method definition

**Creating class and object in Java:


Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along
with its attributes and methods. For example: in real life, a car is
an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.

Definition:
class is a plan or blueprint from which the object is created.
Class can be defined as a collection of objects.
Class is a logical entity.
Class name always starts with an Upper-case alphabet or letter.
If a class contains multiple words, then the starting letter of
every word must be Uppercase letter.
Class can contain list of variables fields) and methods, variables
and methods can be considered as the members of a class.
Whenever we want to access the member of the class, we specify
class name followed by dot operator (.)
Always file name in our program must have the same name as
the class name, and we must use .java extension for our file
name.
Syntax of creating a class:

access_specifier class class_name


{
variables declaration;
method declaration;
}

Object:
Object can be defined as the instance of a class.
Object is a real world or physical entity.
Objects get the properties of a class.
Whenever object is created then only memory is allocated for the
variables of the class.
The process of creating object or instance of the class is called
instantiation.

Syntax of creating an object:

Class_name object_name = new Class_name( );

**Object Oriented Programming (OOP) Principles


Data Abstraction:
Data abstraction means representing essential features and hiding
implementation or background details.

Data Encapsulation:
Wrapping or binding or combining variables and methods under a
single unit called class. Major advantage of encapsulation is data
hiding which can be achieved with the help of access specifiers
private or protected.

Data Inheritance:
The process of creating a new class from another or old class is called
Inheritance. Old class can also be called as parent, base or super class.
New class can be called as child, derived or sub class. Major
advantage of data inheritance is data reusability.

Types of Inheritance:
a. Single inheritance: we have one base and one derived class.
b. Multiple Inheritance: We have one derived class but 2 or
more base class.
c. Multilevel inheritance: Process of creating a class from
derived class.
d. Hierarchical inheritance: We have one parent class but 2 or
more derived class.
e. Hybrid inheritance: It is a combination of more than one
type of inheritance.
Polymorphism:
Polymorphism allows us to perform a single action in different ways.
In other words, polymorphism allows you to define one interface and
have multiple implementations. The word “poly” means many and
“morphs” means forms, So it means many forms.

In Java Polymorphism is mainly divided into two types:


 Compile-time Polymorphism
 Runtime Polymorphism

Compile-Time Polymorphism in Java


It is also known as static polymorphism. This type of polymorphism
is achieved by function overloading or operator overloading.
Runtime Polymorphism in Java
It is also known as Dynamic Method Dispatch. It is a process in
which a function call to the overridden method is resolved at
Runtime. This type of polymorphism is achieved by Method
Overriding. Method overriding, on the other hand, occurs when a
derived class has a definition for one of the member functions of the
base class. That base function is said to be overridden.

Dissecting the “Hello, World” Program

// our first java program. Call this file “[Link]”

public class HelloWorld


{
public static void main(String[ ] args)
{
[Link](“Hello, World!”);
}
}

 For most computer languages, the name of the file that holds the
source code to a program is immaterial. However, this is not the
case with Java. The first thing that you must learn about Java is
that the name you give to a source file is very important. For this
example, the name of the source file should be
[Link].
 In Java, all code must reside inside a class. By convention, the
name of that class should match the name of the file that holds
the program. You should also make sure that the capitalization
of the filename matches the class name. Java is case-sensitive
language.

Let’s examine this program


 The line starting with // is a single-line comment. All characters
between // and the end of the line are ignored by the compiler
and are meant for human readers only.
 Java is an object-oriented language. In your program, you
manipulate objects by having them do work. Each object that
you manipulate belongs to a specific class, and we say that the
object is an instance of that class. A class defines what an
object’s state can be and what it can do. In java, all code is
defined inside classes. This program is made up of a single class
HelloWorld.
The next line of code is shown here

public static void main(String args[ ])


{
 This line begins the main( ) method. All Java applications begin
execution by calling main( ). The public keyword is an access
specifier, which allows the programmer to control the visibility
of class members. When a class member is preceded by public,
then that member may be accessed by code outside the class in
which it is declared. In this case, main( ) must be declared as
public, since it must be called by code outside of its class when
the program is started. The keyword static allows main( ) to be
called without having to instantiate a particular instance of the
class. This is necessary since main( ) is called by the Java
Virtual Machine before any objects are made. The keyword void
simply tells the compiler that main( ) does not return a value.
 Any information that you need to pass to a method is received
by variables specified within the set of parentheses that follow
the name of the method. These variables are called parameters.
If there are no parameters required for a given method, you still
need to include the empty parentheses. In main( ), there is only
one parameter, albeit a complicated one. String args[ ] declares
a parameter named args, which is an array of instances of the
class String. Objects of type String store character strings. In
this case, args receives any command-line arguments present
when the program is executed.
 A complex program will have dozens of classes, only one of
which will need to have a main( ) function to get things started.
The next line of code is shown here

[Link](“Hello, World!”);

 This line outputs the string “Hello, World!” followed by a new


line on the screen. Output is actually accomplished by the built-
in println( ) method which is a method present in PrintStream
class. In this case, println( ) displays the string which is passed
to it. As you will see, println( ) can be used to display other
types of information, too. The line begins with [Link].
While too complicated to explain in detail currently, briefly,
System is a predefined class that provides access to the
system, and out is the output stream which is a static
variable of type PrintStream class that is connected to the
console.

**JDK, JRE and JVM:

Java Development Kit (JDK): JDK provides an environment to


develop, compile and execute java applications. It is a combination
of java compiler (javac) and Java Runtime Environment (JRE). Java
compiler accepts a program with .java extension and it will convert
the program in high level language to bytecodes or class file (.class
extension). Bytecode contains mnemonics or symbols.

Java Runtime Environment (JRE): JRE provides an environment to


execute java applications. To execute java applications, JRE
contains Java Virtual Machine (JVM).
JVM will accept the bytecodes (.class file), JVM interprets the
bytecodes line by line and it will convert the program to machine
code (0s and 1s). Java is an example for Interpreted and Compiled
language.

ARCHITECTURE DIAGRAM:

Compiling and Running a Java Program

 Once you have installed the JDK, Open a terminal window and
run the commands

javac [Link]
java HellWorld

 Note that 2 steps are involved to execute the program. The javac
command compiles the java source code into an intermediate
machine-independent representation called bytecodes, and saves
them in class files. The javac compiler creates a file called
[Link] that contains the bytecode version of the
program. The java command launches a virtual machine that
loads the class files, and executes the bytecodes.
 Once compiled, byte codes can run on any JVM, whether on
your desktop computers or on a device in a galaxy far, far away.
The promise of “write once, run anywhere” was an important
design criterion for java.

**Input and Output


To make our sample programs more interesting, they should be
able to interact with the user. In the following sections, you will
see how to read terminal input and how to produce formatted
output.

Reading Input
When you call [Link], output is sent to the “standard
output stream” and shows up in a terminal window. Reading
from the “standard input stream” isn’t quite as simple
because the corresponding [Link] object only has methods
to read individual bytes. To read strings and numbers,
construct a Scanner that is attached to [Link]:

Scanner in = new Scanner([Link]);


The nextLine m ethod reads a line of input.

[Link]("What is your
name?"); String name =
[Link]();
Here, it makes sense to use the nextLine method because the input
might contain spaces. To read a single word (delimited by
whitespace), call

String firstName = [Link]();


To read an integer, use the nextInt method.

[Link]("How old are


you?");

int age = [Link]();


Similarly, the nextDouble method reads the next floating-point
number.
You can use the hasNextLine, hasNext, hasNextInt, and
hasNextDouble methods to check that there is another line,
word, integer, or floating-point number available.
if ([Link]()) {
int age = [Link]();
...
}
The Scanner class is located in the [Link] package. In order to
use the class, add the line
import [Link]
to the top of your program file.

Formatted Output
You have already seen the println method of the [Link] object
for writing a line of output. There is also a print method that does
not start a new line. That method is often used for input prompts:
[Link]("Your age: "); // Not
println
int age = [Link]();
Then the cursor rests after the prompt instead of the next line.

** Variable Types, Scope & Lifetime of a Variable

Scope of a variable refers to which areas or sections of a


program can the variable be accessed.

The lifetime of a variable refers to how long the variable


stays alive in memory.

General convention for a variable’s scope is, it is accessible


only within the block which it is declared.

Variables in java are of 3 types:


a. Local variables:
These variables are declared inside the method and the scope of the
variable is until we close the method definition.
Can be directly accessed without object creation.

b. Instance variables:
These variables are declared inside the class.
Accessing is done through object creation.
They are used to store unique data for each instance of the class.
c. Static Variables/Class Variables:
Declared using static keyword.
Can be declared inside a class.
Directly accessed without object creation.
All instances of the class share the same static variable.

Program to demonstrate different variable types


public class variable
{
static int c = 30; //static variable
int a = 10; //instance variable
public static void main(String[] args)
{
Variable v1 = new Variable();
int b = 20; //local variable
[Link](v1.a);
[Link](b);
[Link](c);
}
}

Program to demonstrate scope and lifetime of a variable


public class ScopeLifetime {

public static void main(String[] args) {


int x;//local variable
//beginning of inner block
{
int y = 100;
x = 200;
[Link]("x =" + x);
[Link]("y = " + y);
}
//end of inner block
[Link]("x =" + x);

PROGRAMMMING EXAMPLES:

Write a JAVA program to print the following text message


“REVA UNIVERISTY” on the console
public class A
{
public static void main(String args[])
{
[Link](“REVA UNIVERSITY”);
}
}

Write a JAVA program to read and print an integer number


import [Link];
public class Integer
{
public static void main(String args[ ])
{
int num;
[Link]("Enter the integer: ");
Scanner s = new Scanner([Link]);
num = [Link]();
[Link]("Entered integer is: " + num);
}
}

Write a JAVA program to read and find the sum of 2 integer


numbers
import [Link];
public class Sum
{
public static void main(String args[])
{
int x, y, z;
[Link]("Enter two integers to calculate their sum");
Scanner in = new Scanner([Link]);
x = [Link]();
y = [Link]();
z = x + y;
[Link]("Sum of the integers = " + z);
}
}

Write a JAVA program to read and print a character


To read a character, we use next( ).charAt(0). next( ) function returns
the next token/word in the input as a string and charAt(0) function
returns the first character in that string.
import [Link];
public class Character
{
public static void main(String args[])
{
char c;
[Link](“Enter a character”);
Scanner sc=new Scanner([Link]);
c=[Link]( ).charAt(0);
[Link](“Character=” + c);
}
}

Write a JAVA program to read and print a string


import [Link];
public class String_Example
{
public static void main(String args[])
{
String str;
[Link](“Enter a string:”);
Scanner reader=new Scanner([Link]);
str=[Link]();
[Link](“The string you entered is=” + str);
}
}

Write a JAVA program to find the area of circle

public class Area

public static void main(String args[])

{
double pi, r, a;

r = 10.8; // radius of circle

pi = 3.1416; // pi, approximately

a = pi * r * r; // compute area

[Link]("Area of circle is " + a);

Write a JAVA program to show the usage of Boolean variables


public class Bool
{

public static void main(String args[])


{

boolean b;

b = false;

[Link]("b is " + b);

b = true;

[Link]("b is " + b);

// a boolean value can control the if statement

if(b) [Link]("This is executed.");


b = false;

if(b) [Link]("This is not executed.");

// outcome of a relational operator is a boolean value

[Link]("10 > 9 is " + (10 > 9));


}
}
Write a JAVA program to show the usage of constants
public class Constants
{
public static void main(String args[])
{
final int WIDTH=100;
final int LENGTH=150;
int a=50;
a=40;
[Link]("value of constant WIDTH=" +
WIDTH);
[Link]("value of constant LENGTH=" +
LENGTH);
[Link]("value of variable a=" + a);
//WIDTH=50;
}
}

**Operator:

An operator is a symbol which specifies the type of operation being


performed on various types of data.
Java uses the familiar operators of any C-based language. We will
review them in the following sections.
Operators Associativity
[] . () (method call) Left
! ~ ++ -- + (unary) - (unary) () Right
(cast) new
* / % (modulus) Left
+- Left

<< >> >>> (arithmetic shift) Left

< > <= >= instanceof Left


== != Left
& (bitwise and) Left
^ (bitwise exclusive or) Left
| (bitwise or) Left
&& (logical and) Left
|| (logical or) Left
? : (conditional) Left
= += -= *= /= %= <<= >>= Right
>>>= &= ^= |=

In this table, operators are listed by decreasing precedence.


For example, since + has a higher precedence than <<, the
value of 3 + 4 << 5 is (3 + 4) << 5. An operator is left-
associative when it is grouped left to right. For example, 3 - 4
- 5 means (3 - 4) - 5. But -= is right- associative, and i -= j -=
k means i -= (j -= k).
Assignment Operator
The statement
x = expression;
sets x to the value of the right-hand side, replacing the previous
value. When = is preceded by an operator, the operator
combines the left- and right-hand sides and the result is
assigned. For example,
amount -= 10;
is the same as
amount = amount - 10;

Basic Arithmetic Operators


 Addition, subtraction, multiplication, and division are
denoted by + - * /.
For example, 2 * n + 1 means to multiply 2 and n and
add 1.
You need to be careful with the / operator. If both
operands are integer types, it denotes integer division,
discarding the remainder. For example, 17 / 5 is 3,
whereas 17.0 / 5 is 3.4. An integer division by zero gives
rise to an exception which, if not caught, will terminate
your program.
 A floating-point division by zero yields an infinite value or
NaN (Not a Number) without causing an exception.
 The % operator yields the remainder. For example, 17 % 5 is
2, the amount that remains from 17 after subtracting 15 (the
largest integer multiple of 5 that “fits” into 17). If the
remainder of a % b is zero, then a is an integer multiple of b.
 Java has increment and decrement operators:
n++; // Adds one to n

n--; // Subtracts one from n

As in other C-based languages, there is also a prefix form of


these operators. Both n++ and ++n increment the variable n,
but they have different values when they are used inside an
expression. The first form yields the value before the
increment, and the second the value after the increment.

Write a JAVA program to perform arithmetic operations


public class Arithmetic_Operations
{
public static void main(String args[])
{
int a=10, b=20;
int c=a+b;
int d=b-a;
int e=a*b;
int f=b/a;
int g=a%b;
int h=b%a;
[Link](" Addition of a & b = "+c);
[Link](" Subtraction of a & b = "+d);
[Link](" Multiplication of a & b = "+e);
[Link](" Division of a & b = "+f);
[Link](" Modulus of a & b = "+g);
[Link](" Modulus of b & a = "+h);
}
}
Write a JAVA program to show the usage of increment
operator
public class Increment
{
public static void main(String args[])
{
char ch1;
ch1 = 'X';
[Link]("ch1 contains " + ch1);
ch1++; // increment ch1
[Link]("ch1 is now " + ch1);
}
}

Relational Operators
 The relational operators determine the relationship that
one operand has to the other. Specifically, they determine
equality and ordering. There are six relational operators ==
(Equal to), != (Not Equal to) , < (Less than), <= (Less than
or equal to), > (Greater than) and >= (Greater than or equal
to). The outcome of these operations is a boolean value.
 The relational operators are most frequently used in the
expressions that control the if statement and the various
loop statements. Any type in Java, including integers,
floating-point numbers, characters, and Booleans can be
compared using the equality test, ==, and the inequality
test, !=. Notice that in Java equality is denoted with two
equal signs, not one. (Remember: a single equal sign is the
assignment operator.) Only numeric types can be
compared using the ordering operators. That is, only
integer, floating-point, and character operands may be
compared to see which is greater or less than the other. As
stated, the result produced by a relational operator is a
boolean value.
 You can combine expressions of type boolean with the
&& (and), || (or), and !not) operators.
For example,
<= n && n < length
is true if n lies between zero (inclusive) and length
(exclusive).
 If the first condition is false, the second condition is not
evaluated. This “short circuit” evaluation is useful when
the second condition could cause an error.
 Finally, the conditional operator takes three operands:
a condition and two values. The result is the first of
the values if the condition is true, the second
otherwise. For example,
time < 12 ? "am" : "pm"
yields the string "am" if time < 12 and the string "pm"
otherwise.

Logical Operators
Logical operators are used to combine two or more relational
expressions. There are 3 Logical Operators - Logical AND(&&),
Logical OR(||) and Logical NOT(!).
A B A&&B A||B !A
False False False False True
True False False True False
False True False True True
True True True True False
Result is True in Logical AND if both the operands are True
otherwise False. In case of Logical OR, result is True if at least
one opened is True otherwise it is False.

Bitwise Operators
Bitwise operators are used to manipulate the bits of given data. In
case of bitwise operators, the operand is first converted por
represented in binary and then the bitwise operation is performed
on the bits of given data. There are six bitwise operators – Bitwise
AND(&), Bitwise OR(|), Bitwise XOR(^), Bitwise unary NOT(~),
Bitwise Left shift(<<) and Bitwise Right shift (>>).
A B A&B A|B A^B ~A
0 0 0 0 0 1
1 0 0 1 1 0
0 1 0 1 1 1
1 1 1 1 0 0
In case of Bitwise XOR the result is false if both the bits are same,
otherwise it is true.
Bitwise Left Shift (<<)
It has this general form:
value << num
Here, num specifies the number of positions to left-shift the value in
value. That is, the << moves all of the bits in the specified value to the
left by the number of bit positions specified by num. For each shift
left, the high-order bit is shifted out (and lost), and a zero is brought
in on the right. If we shift the value towards left by one bit position it
is equivalent to multiplying by 2.
Bitwise Right Shift (>>)
The right shift operator, >>, shifts all of the bits in a value to the right
a specified number of times. Its general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in
value. That is, the >> moves all of the bits in the specified value to the
right the number of bit positions specified by num.
The following code fragment shifts the value 32 to the right by two
positions, resulting in a being set to 8:
int a = 32;
a = a >> 2; // a now contains 8
If we shift the value towards right by one bit position it is equivalent
to dividing by 2. If we shift by 2 bit position, it is equivalent to
dividing by 4.

Write a JAVA program to show the usage of relational, logical


and bitwise operators
public class A
{
public static void main(String args[])
{
int a=10,b=5;
boolean c=(a>b);
boolean d=(a<b);
boolean e=(a!=b);
boolean f=(a==b);
boolean n=true,p=false;
boolean g=(n&&p);
boolean h=(n||p);
boolean i=(!n);
int j=(a&b);
int k=(a|b);
int l=(a<<1);
int m=(a>>1);
[Link]("Result of relational greater than
operation=" + c);
[Link]("Result of relational less than
operation=" + d);
[Link]("Result of relational not equal to
operation=" + e);
[Link]("Result of relational equality
operation=" + f);
[Link]("Result of logical and operation=" + g);
[Link]("Result of logical or operation=" + h);
[Link]("Result of logical not operation=" + i);
[Link]("Result of bitwise and operation=" + j);
[Link]("Result of bitwise or operation=" + k);
[Link]("Result of bitwise left shift operation="
+ l);
[Link]("Result of bitwise right shift than
operation=" + m);
[Link]("Result of relational greater than
operation=" + c);
}
}

**Control Flow Statements


In the following sections, you will see how to implement branches and
loops. The Java syntax for control flow statements is very similar to
that of other commonly used languages, in particular C/C++ and
JavaScript.

Branching or decision-making statements


The if statement has a condition in parentheses, followed by either
one statement or a group of statements enclosed in braces.
if (count > 0)

{
double average = sum / count;
[Link](average);
}
You can have an else branch that runs if the condition is not
fulfilled.

if (count > 0) {
double average = sum / count;
[Link](average);
} else {
[Link](0);
}
The statement in the else branch may be another if statement:

if (count > 0)

{
double average = sum / count;
[Link](average);
}
else if (count == 0)
{
[Link](0);
}
else
{
[Link]("Huh?");
}
When you need to test an expression against a finite number of
constant values, use the switch statement.

switch
(cou
nt)

case
0:
output =
"None";
break;
case 1:
outpu
t =
"One"
;
break;
case 2:
case 3:
case 4:
case 5:
output =
[Link](count);
break;
default:
output =
"Many";
break;
}
Execution starts at the matching case label or, if there is no match, at
the default label (if it is present). All statements are executed until a
break or the end of the switch statement is reached.
In the preceding example, the case labels were integers. You can
use values of any of the following types:
• A constant expression of type char, byte, short, or int
• A string literal
• A value of an enumeration

Write a JAVA program to find the largest of 2 numbers using if-


else statement
import [Link];
public class If_Else
{
public static void main(String args[])
{
int a,b;
[Link](" enter 2 numbers: ");
Scanner in = new Scanner([Link]);
a=[Link]();
b=[Link]();
if(a>b)
[Link](“Largest of 2 numbers=” + a);
else
[Link](“Largest of 2 numbers=” + b);
}
}

Write a JAVA program to show the usage of else-if ladder


statement
import [Link];
public class Else_If
{
public static void main(String args[])
{
[Link](" enter a integer value : ");
Scanner in = new Scanner([Link]);
int month = [Link]();
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
[Link]("Month entered is a " + season +"
season.");
}
}

Write a JAVA program to find largest of 3 numbers using nested-


if statement
import [Link];
public class Nested_If
{
public static void main(String args[])
{
int a,b,c;
Scanner s=new Scanner([Link]);
[Link](“Enter 3 numbers:”);
a=[Link]();
b=[Link]();
c=[Link]();
if(a>b)
{
if(a>c)
[Link](“Largest number=” + a);
else
[Link](“Largest number=” + c);
}
else
{
if(b>c)
[Link](“Largest number=” + b);
else
[Link](“Largest number=” + c);
}
}
}
Write a JAVA program to show the implementation of basic
calculator using switch statement
import [Link];
public class Calculator
{
public static void main(String args[ ])
{
double a,b,result=0;
char operator;
Scanner reader = new Scanner([Link]);
[Link]("Enter the operands: ");
a= [Link]( );
b= [Link]( );
[Link]("Enter an operator (+, -, *, /): ");
operator = [Link]( ).charAt(0);
switch(operator)
{
case '+':
result = a+b;;
break;
case '-':
result = a-b;
break;
case '*':
result = a*b;
break;
case '/':
result = a/b;
break;
// operator doesn't match any case constant (+, -, *, /)
default:
[Link]("Error! operator is not
correct");
}
[Link]("%f %c %f = %f", a, operator, b,
result);
}
}

Write a JAVA program to show the usage of switch statement


public class SampleSwitch
{
public static void main(String args[])
{
for(int i=0; i<6; i++)
{
switch(i)
{
case 0: [Link]("i is zero.");
break;
case 1: [Link]("i is one.");
break;
case 2: [Link]("i is two.");
break;
case 3: [Link]("i is three.");
break;
default: [Link]("i is greater than
3.");
}
}
}
}

Write a JAVA program to count the number of vowels and


consonants in a string
class CountVowelConsonant
{
public static void main(String[] args)
{
int vcount = 0, ccount = 0;
String str1 = "Hi I am studying 2nd year Engineering in
REVA";
str = [Link]();
for(int i = 0; i < [Link](); i++)
{
if([Link](i) == 'a' || [Link](i) == 'e' || [Link](i)
== 'i' || [Link](i) == 'o' || [Link](i) == 'u')
{
vcount++;
}
else
{
if([Link](i)!=' ')
{
ccount++;
}
}

}
[Link]("Number of vowels= " + vcount);
[Link]("Number of consonants= " + ccount);
}
}
Loops
The while loop keeps executing its body while more work needs
to be done, as determined by a condition.
For example, consider the task of summing up numbers until the
sum has reached a target. For the source of numbers, we will use a
random number generator, provided by the Random class in the
[Link] package.

Random generator = new Random();


This call gets a random integer between 0 and 9:

int next = [Link](10);


Here is the loop for forming the sum:

while (sum < target) {


int next =
[Link](10);
sum += next;
count++;
}
This is a typical use of a while loop. While the sum is less than the
target, the loop keeps executing.
Sometimes, you need to execute the loop body before you can
evaluate the condition. Suppose you want to find out how long it
takes to get a particular value. Before you can test that condition,
you need to enter the loop and get the value. In this case, use a
do/while loop:

int next;
do
{
next =
[Link](10);
count++;
} while (next != target);
The loop body is entered, and next is set. Then the condition is
evaluated. As long as it is fulfilled, the loop body is repeated.
In the preceding examples, the number of loop iterations was not
known. However, in many loops that occur in practice, the
number of iterations is fixed. In those situations, it is best to use
the for loop.
This loop computes the sum of a fixed number of random values:

for (int i = 1; i <= 20; i++)

{
int next =
[Link](10);
sum += next;
}
This loop runs 20 times, with i set to 1, 2, ..., 20 in each loop
iteration.
You can rewrite any for loop as a while loop. The loop above is
equivalent to

int i = 1;
while (i <= 20) {
int next =
[Link](10);
sum += next;
i++;
}
However, with the while loop, the initialization, test, and update of
the variable i
are scattered in different places. With the for loop, they stay neatly
together.
The initialization, test, and update can take on arbitrary forms. For
example, you can double a value while it is less than the target:

for (int i = 1; i < target; i *= 2)


{ [Link](i);
}
Instead of declaring a variable in the header of the for loop, you
can initialize an existing variable:
for (i = 1; i <= target; i++) // Uses existing variable i
You can declare or initialize multiple variables and provide
multiple updates, separated by commas. For example,

for (int i = 0, j = n - 1; i < j; i++, j--)


If no initialization or update is required, leave them blank. If you
omit the condition, it is deemed to always be true.
for (;;) // An infinite loop
You will see in the next section how you can break out of such a
loop.

Write a JAVA program to print the numbers from 1 2 3 ……n


using while loop
import [Link];
class While_Example
{
public static void main(String args[])
{
int i=1,n;
Scanner s=new Scanner([Link]);
[Link](“Enter the value of n:”);
n=[Link]();
while(i<=n)
{
[Link](i);
i++;
}
}
}

Write a JAVA program to show the usage of while loop


public class while_ex
{
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("How much money do you need to
retire? ");
double goal = [Link]();
[Link]("How much money will you
contribute every year?");
double payment = [Link]();

[Link]("Interest rate in %: ");


double interestRate = [Link]();
double balance = 0;
int years = 0;
// update account balance while goal isn't reached
while (balance < goal)
{
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
[Link]("You can retire in " + years + "
years.");
}
}

Write a JAVA program to print the numbers from 1 2 3 ……n


using do-while loop
import [Link];
class Do_While_Example
{
public static void main(String args[])
{
int i=1,n;
Scanner s=new Scanner([Link]);
[Link](“Enter the value of n:”);
n=[Link]();
do
{
[Link](i);
i++;
}while(i<=n);
}
}
Write a JAVA program to show the usage of do-while loop
import [Link];
class Do_While
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("How much money will you contribute
every year?");
double payment = [Link]();
[Link]("Interest rate in %: ");
double interestRate = [Link]();
double balance = 0;
int year = 0;
String input;
// update account balance while user isn't ready to retire
do
{
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
// print current balance
[Link]("After year %d, your balance is
%,.2f%n", year, balance);
// ask if ready to retire and get input
[Link]("Ready to retire? (Y/N) ");
input = [Link]();
}while ([Link]("N"));
}
}

Write a JAVA program to print odd numbers from 1 to n using


for loop
import [Link];
class For_Example
{
public static void main(String args[])
{
int i,n;
Scanner s=new Scanner([Link]);
[Link](“Enter the value of n:”);
n=[Link]();
for(i=1;i<=n;i+=2)
{
[Link](i);
}
}
}

Breaking and Continuing


If you want to exit a loop in the middle, you can use the break
statement. For example, suppose you want to process words until
the user enters the letter Q. Here is a solution that uses a boolean
variable to control the loop:
boolean done =
false;
while (!done)
{
String input =
[Link]();
if
("Q".equals(inpu
t))
{
done = true;
}
else
{
Process input
}
}
This loop carries out the same task with a break statement:

while (true)

{
String input = [Link]();
if ([Link]("Q")) break; // Exits loop
Process input
}
// break jumps here
When the break statement is reached, the loop is exited immediately.
The continue statement is similar to break, but instead of jumping
to the end of the loop, it jumps to the end of the current loop
iteration. You might use it to skip unwanted inputs like this:

while
([Link]())

int input =
[Link]();
if (input < 0) continue; // Jumps to test of [Link]()
Process input
}
In a for loop, the continue statement jumps to the next update
statement:

for (int i = 1; i <= target; i++)

int input = [Link]();


if (n < 0) continue; // Jumps to i++
Process input
}
The break statement only breaks out of the immediately enclosing
loop or switch. If you want to jump to the end of another
enclosing statement, use a labeled break statement. Label the
statement that should be exited, and provide the label with the
break like this:
outer:
while (...)
{
...
while (...)
{
...
if (...) break outer;
...
}
...
}
// Labeled break jumps here
The label can be any name.
A regular break can only be used to exit a loop or switch, but a
labeled break
can transfer control to the end of any statement, even a block
statement:

e
x
i
t
:

{
.
.
.
if (...) break exit;
...
}
// Labeled break jumps here
There is also a labeled continue statement that jumps to the next
iteration of a labeled loop

Write a JAVA program to show the usage of break for


breaking a loop
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<3; i++)
{
[Link]("Pass " + i + ": ");
for(int j=0; j<100; j++)
{
if(j == 10) break; // terminate loop if j is 10
[Link](j + " ");
}
[Link]();
}
[Link]("Loops complete.");
}
}
Write a JAVA program to show the usage of break as a
civilized form of goto
class Break_Civilized_Goto
{

public static void main(String args[])


{

boolean t = true;

first:
{
second:
{

third:
{

[Link]("Before the
break.");

if(t) break second; // break out of


second block

[Link]("This won't
execute");

[Link]("This won't execute");

[Link]("This is after second block.");

Write a JAVA program to show the usage of break


class BreakLoop
{

public static void main(String args[])


{

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


{

[Link]("Pass " + i + ": ");

for(int j=0; j<100; j++)


{

if(j == 10) break; // terminate loop if j is 10

[Link](j + " ");

[Link]();

[Link]("Loops complete.");

Write a JAVA program to show the usage of continue


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

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


{

[Link](i + " ");

if (i%2 == 0) continue;

[Link]("");

Arrays
Array is a collection of elements of same data type. An array is a
group of like-typed variables that are referred to by a common
name. Arrays of any type can be created and may have one or more
dimensions. A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.

Arrays are a fundamental programming construct for collecting


multiple items of the same type. Java has array types built into the
language, and it also supplies an ArrayList class for arrays that grow
and shrink on demand. The ArrayList class is a part of a larger
collection’s framework.

One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables.
To create an array, you first must create an array variable of the
desired type. The general form of a one-dimensional array declaration
is
type var-name[ ];

Here, type declares the base type of the array. The base type
determines the data type of each element that comprises the array.
Thus, the base type for the array determines what type of data the
array will hold. For example, the following declares an array named
month_days with the type “array of int”:
int month_days[];

Although this declaration establishes the fact that month_days is an


array variable, no array actually exists. In fact, the value of
month_days is set to null, which represents an array with no value.
To link month_days with an actual, physical array of integers, you
must allocate one using new and assign it to month_days. new is a
special operator that allocates memory.

You will look more closely at new in a later chapter, but you need to
use it now to allocate memory for arrays. The general form of new as
it applies to one-dimensional arrays appears as follows:
var-name = new type[size];

Here, type specifies the type of data being allocated, size specifies the
number of elements in the array, and array-var is the array variable
that is linked to the array. That is, to use new to allocate an array, you
must specify the type and number of elements to allocate. The
elements in the array allocated by new will automatically be
initialized to zero. This example allocates a 12-element array of
integers and links them to month_days.
month_days = new int[12];
After this statement executes, month_days will refer to an array of 12
integers. Further, all elements in the array will be initialized to zero.
Let’s review: Obtaining an array is a two-step process. First, you must
declare a variable of the desired array type. Second, you must allocate
the memory that will hold the array, using new, and assign it to the
array variable. Thus, in Java all arrays are dynamically allocated.

Once you have allocated an array, you can access a specific element
in the array by specifying its index within square brackets. All array
indexes start at zero. For example, this statement assigns the value 28
to the second element of month_days.
month_days[1] = 28;
The next line displays the value stored at index 3.
[Link](month_days[3]);

Write a JAVA to read and print the elements of One


Dimensional(1D) array
import [Link];
public class Array
{
public static void main(String args[])
{
int arr[]=new int[15];
int n,i;
Scanner s=new Scanner([Link]);
[Link]("How many elements you want to read
into the array?");
n=[Link]();
[Link]("Enter " +n + " Element to store in
array:");
for(i=0;i<n;i++)
{
arr[i]=[Link]();
}
[Link]("Elements of array are:");
for(i=0;i<n;i++)
{
[Link](arr[i] + " ");
}
}
}

JAVA program to display the number of days of every month


using arrays
public class Array
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
[Link]("April has " + month_days[3] + "
days.");
}
}

It is possible to combine the declaration of the array variable with the


allocation of the array itself, as shown here:
int month_days[] = new int[12];
This is the way that you will normally see it done in professionally
written Java programs. Arrays can be initialized when they are
declared. The process is much the same as that used to initialize the
simple types. An array initializer is a list of comma-separated
expressions surrounded by curly braces. The commas separate the
values of the array elements. The array will automatically be created
large enough to hold the number of elements you specify in the array
initializer. There is no need to use new. For example, to store the
number of days in each month, the following code creates an
initialized array of integers:

// An improved version of the previous program.


public class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
[Link]("April has " + month_days[3] + " days.");
}
}
When you run this program, you see the same output as that generated
by the previous version. Java strictly checks to make sure you do not
accidentally try to store or reference values outside of the range of the
array. The Java run-time system will check to be sure that all array
indexes are in the correct range. For example, the run-time system
will check the value of each index into month_days to make sure that
it is between 0 and 11 inclusive. If you try to access elements outside
the range of the array (negative numbers or numbers greater than
the length of the array), you will cause a run-time error.
When you construct an array with the new operator, it is filled with a
default value.
1. Arrays of numeric type (including char) are filled with zeroes.
2. Arrays of boolean are filled with false.
3. Arrays of objects are filled with null references.

Write a JAVA program to find the average of a set of numbers


class Average
{
public static void main(String args[])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
{
result = result + nums[i];
}
[Link]("Average is " + result / 5);
}
}
Enhanced for loop (for-each version of the for loop)
Beginning with JDK 5, a second form of for was defined that
implements a “for-each” style loop. As you may know, contemporary
language theory has embraced the for-each concept, and it is quickly
becoming a standard feature that programmers have come to expect.
A for-each style loop is designed to cycle through a collection of
objects, such as an array, in strictly sequential fashion, from start to
finish. Unlike some languages, such as C#, that implement a for-each
loop by using the keyword foreach, Java adds the for-each capability
by enhancing the for statement. The advantage of this approach is that
no new keyword is required, and no pre-existing code is broken. The
for-each style of for is also referred to as the enhanced for loop.

The general form of the for-each version of the for is shown here:
for(type itr-var : collection) statement-block

Here, type specifies the type and itr-var specifies the name of an
iteration variable that will receive the elements from a collection,
one at a time, from beginning to end. The collection being cycled
through is specified by collection. There are various types of
collections that can be used with the for, but the only type used in this
chapter is the array. With each iteration of the loop, the next element
in the collection is retrieved and stored in itr-var. The loop repeats
until all elements in the collection have been obtained.

Because the iteration variable receives values from the collection,


type must be the same as (or compatible with) the elements stored in
the collection. Thus, when iterating over arrays, type must be
compatible with the base type of the array.
To understand the motivation behind a for-each style loop, consider
the type of for loop that it is designed to replace. The following
fragment uses a traditional for loop to compute the sum of the values
in an array:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int i=0; i < 10; i++)
{
sum += nums[i];
}

To compute the sum, each element in nums is read, in order, from


start to finish. Thus, the entire array is read in strictly sequential order.
This is accomplished by manually indexing the nums array by i, the
loop control variable.
The for-each style for automates the preceding loop. Specifically, it
eliminates the need to establish a loop counter, specify a starting and
ending value, and manually index the array. Instead, it automatically
cycles through the entire array, obtaining one element at a time, in
sequence, from beginning to end. For example, here is the preceding
fragment rewritten using a for-each version of the for:

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
{
sum += x;
}

With each pass through the loop, x is automatically given a value


equal to the next element in nums. Thus, on the first iteration, x
contains 1; on the second iteration, x contains 2; and so on. Not only
is the syntax streamlined, but it also prevents boundary errors.

Here is an entire program that demonstrates the for-each version of


the for just described:
public class ForEach
{
public static void main(String args[])
{
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums)
{
[Link]("Value is: " + x);
sum += x;
}
[Link]("Summation of values in the array= " +
sum);
}
}

Two-Dimensional Arrays
Two – dimensional array is the simplest form of a multidimensional
array. A two – dimensional array can be seen as an array of one –
dimensional array for easier understanding. Arrays with 2 sets of
square brackets are called two-dimensional arrays.

Declaration Syntax:
type arr-name[ ][ ]=new type[size1][size2];

Example:
int arr[][]=new int[4][6];

Initialization syntax:
array_name[row_index][column_index]=value;
Example:
arr[0][0]=1;

Accessing two-dimensional array elements


Elements in two-dimensional arrays are commonly referred by arr[i]
[j] where ‘i’ is the row number and ‘j’ is the column number.

Write a JAVA to read and print the elements of Two


Dimensional(2D) array
import [Link];
class Array
{
public static void main(String args[])
{
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner s = new Scanner([Link]);
[Link]("Enter the number of rows:");
row = [Link]();
[Link]("Enter the number of columns:");
col = [Link]();
[Link]("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
arr[i][j] = [Link]();
}
}
[Link]("Array elements are:");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
[Link](arr[i][j]+ " ");
}
[Link]();
}
}
}

Constructor and types of constructors

It is a special method which is useful to initialize objects. Major


advantage of constructor it initializes value to instance variables.
Constructor constructs an objects and which gets called
automatically whenever the object is created.

Rules for defining a constructor:

a. Name of the constructor must be same as class name.


b. Constructor do not return any value, No return type for
constructor not even void.
c. Access specifier or access modifier of the constructor can be
public, private, protected or default.
d. We can’t use modifier final, abstract or synchronized.
e. Constructor gets called automatically whenever the object is
created.
Syntax of creating an object:

Class_name object_name = new Class_name( );

Consider the class name as Rectangle, then to create objects we


use the statement like this

Rectangle r = new Rectangle( );

In the above statement Rectangle( ) is the constructor, because


it has same name as the class name and is getting called during
object creation.

Types of Constructors:

Default on no argument or zero argument or parameter less


constructor: A constructor without any arguments is called as
default constructor.

Program to demonstrate default constructor

public class Rectangle {

double length, breadth;


Rectangle()
{
length = 10;
breadth = 20;
}

double area()
{
return length * breadth;
}

public static void main(String[] args) {

Rectangle obj1 = new Rectangle();


Rectangle obj2 = new Rectangle();
[Link]("Area of 1st Object = " +
[Link]());
[Link]("Area of 2nd Object = " +
[Link]());

}
}

Parameterized constructor:
A constructor with parameters is called parameterized instructor. If
we want to initialize different values for the objects, then we can
use parameterized constructor.

Program to demonstrate parameterized constructor

public class Rectangle1 {

double length, breadth;

Rectangle1(double l,double b)
{
length = l;
breadth = b;
}

double area()
{
return length * breadth;
}
public static void main(String[] args) {

Rectangle1 obj1 = new Rectangle1(5,10);


Rectangle1 obj2 = new Rectangle1(2,4);
[Link]("Area of 1st Object = " +
[Link]());
[Link]("Area of 2nd Object = " +
[Link]());

Copy Constructor:
Whenever we pass object reference as a parameter to the
constructor then it is called Copy constructor.
Copy constructor is used to copy the contents of one object to
another object by the help of a reference variable which is of class
type.

Syntax:

class class-name
{
class-name(class-name ref)
{
statements;
}
}

Program to demonstrate copy constructor

class A
{
int a;
String b;
A( )
{
a = 100;
b = "Vedanth";
[Link](a + " " + b);
}
A(A ref)
{
a = ref.a;
b = ref.b;
[Link](a + " " + b);
}
}

class B
{
public static void main(String args[])
{
A object1 = new A();
A object2 = new A(object1);
}
}

Static Variables and Methods


There will be times when you will want to define a class member that
will be used independently of any object of that class. Normally, a
class member must be accessed only in conjunction with an object of
its class. However, it is possible to create a member that can be used
by itself, without reference to a specific instance. To create such a
member, precede its declaration with the keyword static. When a
member is declared static, it can be accessed before any objects of
its class are created, and without reference to any object. You can
declare both methods and variables to be static. The most common
example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.

Instance variables declared as static are, essentially, global variables.


When objects of its class are declared, no copy of a static variable is
made. Instead, all instances of the class share the same static variable.
Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way. (The keyword super
relates to inheritance and is described in the next chapter.)

If you need to do computation in order to initialize your static


variables, you can declare a static block that gets executed exactly
once, when the class is first loaded. Static methods are methods
that do not operate on objects. For example, the pow method of
the Math class is a static method. The expression
[Link](x, a)

computes the power xa. It does not use any Math object to carry out
its task.

When a variable is declared as static, then a single copy of variable is


created and shared among all objects at class level. Static variables
are, essentially, global variables. All instances of the class share the
same static variable.
Important points for static variables:
 We can create static variables at class-level only.
 Static block and static variables are executed in order they are
present in a program.
 It is a variable which belongs to the class and not to
object(instance).
 Static variables are initialized only once, at the start of the
execution. These variables will be initialized first, before the
initialization of any instance variables.
 A single copy to be shared by all instances of the class.
 A static variable can be accessed directly by the class name and
doesn’t need any object.
The following example shows a class that has a static method, some
static variables, and a static initialization block:

// Demonstrate static variables, methods, and blocks.


class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
[Link]("a = " + a);
[Link]("b = " + b);
}
static
{
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
meth(42);
}
}

As soon as the UseStatic class is loaded, all of the static statements


are run. First, a is set to 3, then the static block executes, which prints
a message and then initializes b to a * 4 or 12. Then main( ) is called,
which calls meth( ), passing 42 to x. The three println( ) statements
refer to the two static variables a and b, as well as to the local
variable x.

Here is the output of the program:


Static block initialized.
a=3
b = 12

Outside of the class in which they are defined, static methods and
variables can be used independently of any object. To do so, you need
only specify the name of their class followed by the dot operator. For
example, if you wish to call a static method from outside its class,
you can do so using the following general form:

[Link]( )

Here, classname is the name of the class in which the static method is
declared. As you can see, this format is similar to that used to call
non-static methods through object-reference variables. A static
variable can be accessed in the same way—by use of the dot operator
on the name of the class. This is how Java implements a controlled
version of global methods and global variables.

Write a JAVA program to create student database to input name,


SRN and college name, where college name should be declared as
static variable
class Student
{
String SRN;
String name;
static String collegeName; //static variable
public static void main(String args[])
{
//create 3 object which will share collegeName value
Student s1= new Student();
Student s2= new Student();
Student s3= new Student();
//assign value to static variable collegeName
[Link]="REVA UNIVERSITY";
//assign values to instance variables
[Link]=”R18CS001”;
[Link]="stud1";
[Link]=”R18CS002”;
[Link]="stud2";
[Link]=”R18CS003”;
[Link]="stud3";
//Print the values of the objects
[Link]("S1 SRN.= "+[Link]+" S1 Name=
"+[Link]+" S1 College Name= "+[Link] );
[Link]("S2 SRN.= "+[Link]+" S2 Name=
"+[Link]+" S2 College Name= "+[Link] );
[Link]("S3 SRN.= "+[Link]+" S3 Name=
"+[Link]+" S3 College Name= "+[Link] );
collegeName="REVA";
[Link]="JAMES";
//Print the values of the objects after change
[Link]("S1 SRN.= "+[Link]+" S1 Name=
"+[Link]+" S1 College Name= "+[Link] );
[Link]("S2 SRN.= "+[Link]+" S2 Name=
"+[Link]+" S2 College Name= "+[Link] );
[Link]("S3 SRN.= "+[Link]+" S3 Name=
"+[Link]+" S3 College Name= "+[Link] );
}
}

The output of the above program is shown below:

You might also like