You are on page 1of 42

Module 1

OOPS CONCEPTS AND JAVA PROGRAMMING

1.1 Basic Concept/Key Attributes of OOP (Object-Oriented Programming):

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts:

 Object
 Class
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism

i. Object: Object is an important runtime entity in object oriented method which has state and
behavior. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Each object holds data and code to operate the data. Object can interact
without having to identify the details of each other‘s data or code. It is sufficient to identify the
type of message received and the type of reply returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

ii. Classes: A class is a set of objects with similar properties (attributes), common behavior
(operations), and common link to other objects. A class can also be defined as a blueprint from
which you can create an individual object. Class doesn't consume any space. The complete set
of data and code of an object can be made a user defined data type with the help of class. The
objects are variable of type class.

Once the class has been defined, we can make any number of objects belonging to that class.
Each object is related with the data of type class with which they are formed. As we learned
that, the classification of objects into various classes is based on its properties (States) and
behavior (methods). Classes are used to distinguish are type of object from another. The
important thing about the class is to identify the properties and procedures and applicability to
its instances

iii. Data Abstraction: Data abstraction refers to the act of representing important description
without including the background details or explanations (Hiding internal details and showing
functionality). Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, cost and functions operate on these attributes. They summarize all the
important properties of the objects that are to be created.
Classes use the concepts of data abstraction and it is called as Abstract Data Type (ADT). In
Java, we use abstract class and interface to achieve abstraction.

iv. Data Encapsulation: Data Encapsulation means wrapping of data and functions into a single
unit (i.e. class). It is most useful feature of class. The data is not easy to get to the outside world
and only those functions which are enclosed in the class can access it.

These functions provide the boundary between Object‘s data and program. This insulation of
data from direct access by the program is called as Data hiding.

v. Inheritance: Inheritance is the process by which objects of one class can get the properties of
objects of another class. Inheritance means one class of objects inherits the data and behaviors
from another class. Inheritance maintains the hierarchical classification in which a class inherits
from its parents. Inheritance provides the important feature of OOP that is reusability. That
means we can include additional characteristics to an existing class without modification. This
is possible deriving a new class from existing one. It is used to achieve runtime polymorphism.

Benefits of Inheritance:

 Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
 Inheritance can save time and effort as the main code need not be written again.
 Inheritance provides a clear model structure which is easy to understand.
 An inheritance leads to less development and maintenance costs.
 With inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance
leads to less development and maintenance costs.
vi. Polymorphism: It is derived from 2 Greek words: “poly” and “morphs”. The word “poly”
means many and “morphs” means forms. So polymorphism means the ability to take more than
one form. Polymorphism plays a main role in allocate objects having different internal
structures to share the same external interface. It is defined as that allows one interface to access
a general class of actions or same name different operations.

1.2 Procedural vs Object Oriented Programming

Procedural Oriented Programming Object-Oriented Programming


1. In procedural programming, the program is 1. In object-oriented programming, the
divided into small parts called functions. program is divided into small parts called
objects.

2. Procedural programming follows a top- 2. Object-oriented programming follows a


down approach. bottom-up approach.

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


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

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

5. Procedural programming does not have any 5. Object-oriented programming provides


proper way of hiding data so it is less data hiding so it is more secure.
secure.

6. In procedural programming, overloading is 6. Overloading is possible in object-


not possible. oriented programming.

7. In procedural programming, there is no 7. In object-oriented programming, the


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

8. In procedural programming, the function is 8. In object-oriented programming, data is


more important than the data. more important than function.
9. Procedural programming is based on the 9. Object-oriented programming is based
unreal world. on the real world.

10. Procedural programming is used for 10. Object-oriented programming is used for
designing medium-sized programs. designing large and complex programs.

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

12. Code reusability absent in procedural 12. Code reusability present in object-
programming, oriented programming.

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

1.3 Java Programming:

Java is a widely-used programming language for coding web applications. It has been a popular choice
among developers for over two decades, with millions of Java applications in use today. Java is a multi-
platform, object-oriented, and network-centric language that can be used as a platform in itself.

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

History of JAVA:

1. In 1990, James Gosling was given a task of creating projects to control consumer electronics.
Gosling and his team Mike Sheridan, and Patrick Naughton at Sun Microsystems started designing
their software using C++ because of its Object-oriented nature. Gosling, however, quickly found
that C++ was not suitable for this project. They faced problems due to program bugs like memory
leak, dangling pointer, multiple inheritance and platform dependent.
2. Gosling decided that he would develop his own, simplified computer language to avoid all the
problems faced in C++.
3. Gosling kept the basic syntax and object oriented features of the C++ language to designing a new
language.
4. He completed and named “OAK” in 1991 at Sun Microsystems.
5. Later Sun Microsystems was discovered that the name “OAK” was already claimed, they changed
the name to “JAVA” in 1995.
6. The Java team realized that the language they had developed would be perfect for web programming
because the World Wide Web had transformed the text-based internet into a graphic rich
environment. Then team came up with the concept of web applets, small programs that could be
included in web pages, and even went so far as to create a complete web browser that demonstrate
the language’s power.
7. The new language was quickly embraced as a powerful tool for developing internet applications.
Support for java was added in the Netscape (Web Browser on UNIX) and in the Internet Explorer.

1.4 Benefits of Using JAVA:

 Java programming language is very simple and object oriented. It is easy to learn and taught in
many colleges and universities.
 Java applications run inside JVM, and now all major operating systems are able to run Java
including Windows, Mac and UNIX.
 Write once, run anywhere: A Java application runs on all Java platforms.
 Java is very secure. Only Java applications that have permission can access the resources of the
main computer. Thus, the main computer is protected from virus attackers and hackers.
 Java technologies have been improved by community involvement. It is suitable for most types
of applications, especially complex systems that are used widely in network and distributed
computing.

1.5 Features of JAVA:


1. Simple: Syntax is based on C and C++, No pointers, No goto, No operator overloading, No
Preprocessor, No global variables.
2. Object-Oriented: Uses OOPs concepts (Inheritance, Polymorphism, Encapsulation, etc)
3. Portable - Platform Independent – Architecture Neutral :

 “Write once, Run anywhere”

 Runs on any platform that has JVM

4. Secured: No explicit pointer, Programs run inside JVM.


5. Robust:
 Java uses the automatic garbage collection that prevents memory leaks.
 Java is strictly typed language, hence Error free.

6. Dynamic:
 Java loads in classes as they are needed.
 JVM is capable of linking dynamic new classes, methods and objects.
7. Compiled and Interpreted:
 Java code is compiled to byte code.
 Byte code are interpreted on any platform by JVM.
 Java programs can be shared over the internet.

8. High Performance:
 Byte code are highly optimized.
 JVM execute Byte code much faster.

9. Distributed: Java programs can be shared over the internet


10. Multithreaded:
 Multithreading means handling more than one job at a time.
 The main advantage of multi-threading is that it shares the same memory.

1.6 A First Simple Program:


Let us look at a simple java program

class Example{
public static void main(String[] args)
{
System.out.println("Welcome to JAVA Class!!!");
}
}

Where,
 class: class keyword is used to declare classes in Java
 public: It is an access specifier. Public means this function is visible to all.
 static: static is again a keyword used to make a method static. To execute a static function
you do not have to create an Object of the class. The main() method here is called by JVM,
without creating any object for class.
 void: It is the return type, meaning this method will not return anything.
 main: main() method is the most important method in a Java program. This is the method
which is executed, hence all the logic must be inside the main() method. If a java class is not
having a main() method, it causes compilation error. Multiple main() methods in the same
class not allowed .
 String[] args: This represents an array whose type is String and name is args.
 System.out.println: This is used to print anything on the console like printf in C language.

Handling Syntax Errors:


If you enter something incorrectly into your program, compiler will report a Syntax error
messages.
Example: class Example{
public static void main(String[] args)
{
System.out.println("Welcome to JAVA Class!!!")
}
}
When you compiled, it will report a syntax error message that

1.7 Java Comments:


Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.

Single-line Comments

 Single-line comments start with two forward slashes (//).

 Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:

Example: // This is a comment

System.out.println("Hello World");

Java Multi-line Comments

 Multi-line comments start with /* and ends with */.

 Any text between /* and */ will be ignored by Java.

 This example uses a multi-line comment (a comment block) to explain the code:

Example: /* The code below will print the words Hello World

to the screen, and it is amazing */

System.out.println("Hello World");

1.8 Data Types:

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

Table: Java’s built-in data types


Type Contains Default Size Range
boolean True or false False 1 bit NA
byte Signed integer 0 8bits -128 to 127
char Unicode Character ‘\u0000’ 16 bits \u0000 to \uFFFF
double IEEE 754 floating point 0.0d 64 bits +4.9E –324 to +1.7976931348623157E+308
float IEEE 754 floating point 0.0f 32 bits +1.4E – 45 to + 3.4028235E+38
int Signed Integer 0 32 bits -2147483648 to 2147483647
-9223372036854775808 to
long Signed Integer 0L 64 bits
9223372036854775807
short Signed Integer 0 16 bits -32768 to 32767

1.9 Variable:

A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
Syntax: type var_name;

Example: int data=50;//Here data is variable Reserved Area


50

Initializing a Variable:
A variable must be declared before to their use. This is necessary because the compiler must know
what type of data or value that can contains it use.
At the time of declaration, we can initialize the value to the variable by using assignment
operator as shownhere:
type var_name = value;

Where, value - is the value that is to var when var is created. Value is known at compile time
Example: int count = 10;
char ch = ‘x’;
flaot f = 1.2F;int a,b = 8;

1.10 The Scope and Lifetime of Variables:


Java allows variables to be declared within any block. A block is begin with an opening brace
and ended by a closed brace.
Scope of variable is the part of the program where the variable is accessible and determined at
the compile time.

Example: class Demo {


public static void main ( String [ ] args
) {int x =10;
if (true) { // creates
new scopeiy = 20;

System.out.println ( y ); // OK
}

System.out.println ( y ); //ERROR, not in scope


System.out.println ( x ); // OK
}}
}
Types of variables:
 Local variables – inside method
 Instance variables - common to class methods.
 Class variables – are static variables
 Reference variable – hold some reference

Example: Class Person {


string name; //Instance Variable
static int count; // Class Variable
void fun()
{
int data; // Local Variable
//other code
}
public static void main(String[] args) {
Person p; // Reference Variable
p=new Person();
p.fun();
}}
1.11 enumerated Types:
The Enum in Java is a data type which contains a fixed set of constants. Enum is short for
"enumerations", which means "specifically listed".
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST),
season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE,
GREEN, WHITE, and BLACK) etc. According to the Java naming conventions, we should have all
constants in capital letters. So, we have enum constants in capital letters.

Example: Declaration outside the class

// A simple enum example where enum is declared


// outside any class (Note enum keyword instead of
// class keyword)

enum Color {
RED,
GREEN,
BLUE;
}
public class Test {
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}

Example: Declaration inside a class

// enum declaration inside a class.

public class Test {


enum Color {
RED,
GREEN,
BLUE;
}

// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output: RED
A Java program to demonstrate working on enum in switch case (Filename Test. Java)
import java.util.Scanner;

// An Enum class
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}

// Driver class that contains an object of "day" and main().


public class Test {
Day day;

// Constructor
public Test(Day day) { this.day = day; }

// Prints a line about Day using switch


public void dayIsLike()
{
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}

// Driver method
public static void main(String[] args)
{
String str = "MONDAY";
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}
}

Output
Mondays are bad.
1.12 Operators:
An operators is a symbol that tells the compiler to perform a specific mathematical, logical or
othermanipulations.
Table: List of operators and example

Category Opera Meaning Example


tors
+ Addition class ArtDemo{
- Subtraction public static void main(String[] args){int iresult, irem;
* Multiplication double dresult, drem;
/ Division
iresult=10/3;
% Modulus irem=10%3;
Arithmetic

++ Increment
-- decrement dresult=10.0/3.0;
drem=10.0%3.0;
System.out.println("Result&remainder:"
+iresult + "\t" +irem);
System.out.println("Result&remainder:"
+dresult + "\t" +drem);
}
}

== Equal to class RelDemo{


public static void main(String[] args){int i=10, j=11;
!= Not equal to
> if(i==j) System.out.println("Equal"); else
Relational

Greater than
System.out.println("NotEqual");
< Less than }
}
>= Greater
thanor
equal to
<= Less than or
equal to
& AND class RelDemo{
public static void main(String[] args){int i=10, j=11;
| OR
XOR(exclusi if(i= =j)
^
veOR) System.out.println("Equal");
Logical

Short- else
|
circuitOR System.out.println("NotEqual");
|
}
Short-circuit }
& AND
&
! NOT
Short Circuit Operator:
Provides Short-Circuit for AND & OR Logical Operators
 In AND (&&) – if the first operand is false, the outcome is false no matter what value the second
operand has.
 In OR ( | | ) – if the first operand is true, the outcome is true no matter what value the second operand
has.
Example:
class ShrtCirDemo{
public static void main(String[] args){
int n=10, Both expressions are
if(d!=0 &&d=2;
(n%d) == 0) evaluated
System.out.println("Modulus is performed ");

d=0; Short circuit operator prevents


if(d!=0 && (n%d) == 0) adivisions by zero

System.out.println("Modulus not performed ");

if(d!=0 & (n%d) == 0) Both expressions are


evaluated
System.out.println("Modulus is performed ");
}
}

• A short circuit operator is one that doesn't necessarily evaluate all of its operands.
• expr1 && expr2 represents a logical AND operation that employs short-circuiting behavior. That is,
expr2 is not evaluated if expr1 is logical 0 (false).

Note: The difference between the normal (&, |) and short-circuit (&&, ||) versions
 The normal operands will always evaluated each operand
 The short-circuit version will evaluate the second operand only when necessary.

The Assignment Operator:


It is single equal sign ( = ) that can used to assign a value to the variable.

Syntax: var = expression / value;


Example: int x, y, z;
x = y = z = 100;

Shorthand Assignments:
Shorthand assignment operators that simplify the coding of certain assignment statements.

Example: x = x + y; equivalent to x += y;

The operator pair += tells the compiler to assign x the value of x plus 10.
Bitwise Operator:

 Bitwise operators are used to test, set, or shift the individual bits that make up a value.
 Bitwise operator can be applied to values of type long, int, short, char, or byte.
 Bitwise operations cannot be used on Boolean, float or double or class type.
Table: List of Operators and example (continued)
Operators &
Categor Description Example
y Meaning
& class UpLwDemo{
Bit by bit evaluated
Bitwise AND public static void main(String[]args)
| {
Bit by bit evaluated
Bitwise OR char ch;
^ for(int i=0; i<10; i++)
Bit by bit evaluated
Exclusive OR {
>> sign bit is shifted in ch=(char) ('A' + i);
Signed Shift high-order
Bitwise

System.out.print(ch);
right positions.
>>> Zero’s are shifted in
ch=(char) ((int) ch | 32);
Unsigned high-order
System.out.print(ch + " ");
Shift right positions.
Zero’s are shifted in
<< }
Low-order
Left shift }
positions.
}//Uppercase to LowercaseOutput:
~
One’s One’s complement Aa Bb Cc Dd Ee Ff Gg Hh Ii Ji
complement
?: Ternary or
Miscellaneous

b = (a == 1) ? 20: 30;
conditional
instanceof The operator checks
whether the object is String name = "James";
of a particular type boolean result=name instanceof String;
System.out.println( result );

1.13 Type conversion in Assignments:


It states that converting from one type to another type. Booleans cannot be converted to other types.
There aretwo types:

 Implicit Type
 Explicit Type
Implicit Type:
An implicit conversion means that a value of one type is changed to a value of another type
automatically. Automatic type casting take place when,
 The two types are compatible
 The target type is larger than the source type.

The lower size is widened to higher size. This is also named as automatic type conversion or
widening.

Example: int x =10; // occupies 4 bytes


double y =x; // occupies 8 bytes, Implicit coversion
System.out.println(y); // prints 10.0

Explicit Type:

Explicit conversions are done via casting. When you are assigning a larger type value to a variable of
smaller type, then you need to perform explicit type casting. It is called as explicit conversion or
narrowing conversionand there may be data loss in this process because the conversion is forceful.
Syntax: (target-type)expression;
Here, target-type specifies the desired type to convert the specified expression to.

Example: double x = 10.5;


int y = (int)x; //explicit casting

The double x is explicitly converted to int y.

1.14 Expressions
Operators, variables, and literals are components of expressions. Type Conversion in expressions:
• Possible to mix 2 or more compatible different data types.
• they are all converted to the same type.
• Java’s type promotion rules can be used for the conversion in an expression.
Example: 2 + (5.0*2.0) -3;
char ch= (char) (ch1 + ch2);
class ExprDemo{
public static void main(String[] args)
{
byte b;
int i;

b=10;
i = b * b; //No cast needed

b=10;
b=(byte) (b * b); // cast is needed
System.out.println("i= " + i + "b= " +b);
}
}

Note: Java’s type Promotion Rules


 All char, byte and short values are promoted to int.
 Any one operand is a long, the whole expression is promoted to long
 Any one operand is a float, the whole expression is promoted to float
 Any one operand is a double, the result is double.

1.15 Handling User Input / Output:


• Java I/O (Input and Output) is used to process the input and produce the output.
• uses the concept of stream to make I/O operation fast.
• The java.io package contains all the classes required for input and output operations
Stream
A stream is a sequence of data. In Java a stream is composed of bytes.
Two types of Streams:
 Byte Streams: handling the input and output of bytes.
 Character Streams: handling the input and output of characters.
Predefined Streams:
There are 3 streams variables:
1. System.in: standard input stream
2. System.out: standard output stream
3. System.err: standard error stream

By default, all these streams are the console.

Input characters from the Keyword:


 To read a character from the keyboard we will use System.in.read().
 System.in is the complement to System.out
 It is the input object attached to the keyboard.
 The read() method waits until the user presses a key and then returns the result.
 The character is returned as an integer, so it must be cast into a char to assign it to a char variable.
Example: class RdChar{
public static void main(String[] args)throws IOException{
char ch;
System.out.println("enter a key");
ch=(char)System.in.read(); //Read a character
System.out.println("your key is= " +ch);

}
}

Output:

Reading string:

String can be read using following classes:


a. InputStreamReader Automatically import the java.io package
b. BufferReader Automatically import the java.io package
c. Scanner imports java.util package

1. InputStreamReader class:
a. Can be used to read data from keyboard.
b. Converts Byte stream to character stream.
Syntax:
InputStreamReader ir=new InputStreamReader(System.in);

2. BufferedReader class:
can be used to read data line by line
Syntax:

BufferedReader input = new BufferedReader(ir);

Methods used for reading string in BufferedReader

Sl No. Method and description


1 int read ( ):- This method reads a single character.
int read (char[] bufArr, int off, int len)
2
- This method reads characters into a portion of an array.
3 String readLine ( ):- This method reads a line of text.
Example:
class RdBr {
public static void main(String[] args)throws java.io.IOException{
String str;
InputStreamReader ir=new InputStreamReader (System.in);
BufferedReader input = new BufferedReader(ir);
// declare in a single line.
//BufferedReader input = new BufferedReader(new
InputStreamReader(System.in));
System.out.println ("Enter a Name");
str = input.readLine();
System.out.println ("String entered is = " + str );
}
}

3. Scanner class:

 The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default.
 It provides many methods to read and parse various primitive values.
Syntax:

Scanner sc_name= new Scanner(System.in);


sc_name.method();

Table. Methods in Scanner class


Method Returns Exception on failure
int nextInt() Returns the next token as an int. InputMismatchException
long nextLong() Returns the next token as a long.
float nextFloat() Returns the next token as a float.
double Returns the next token as a long.
nextDouble()
Finds and returns the next complete token as a NoSuchElementException
String next() string; a token is usually ended by whitespace suchas a
blank or line break.
Returns the rest of the current line, excluding anyline
String nextLine()
separator at the end.
void close() Closes the scanner.
Example:

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

Scanner input = new Scanner(System.in);


System.out.println("Enter your rollno");
int rollno = input.nextInt();

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


String name = input.next();

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


double fee = input.nextDouble();
System.out.println ("Rollno:" + rollno + " name:" + name
+ " fee:" + fee);
input.close();
}
}

Output:

1.16 Java Output Formatting:

At times we want the output of a program to be printed in a given specific format. In the
C programming language this is possible using the printf( ) function. In java there are two methods
that can be used to format the output in Java:

o Using the printf( ) Method


o Using the format( ) Method

Formatting output using System.out.printf( ) Method:

The implementation of this method is very easy as it is similar to the printf( ) function in C
programming.

public class FormattedOutput1


{
public static void main( String args[ ] )
{
// printing the string value on the console
String str = " JavaTpoint " ;
System.out.printf( " \n Printing the String value : %s \n ", str ) ;
// printing the integer value on the console
int x = 512 ;
System.out.printf( " \n Printing the integer value : x = %d \n ", x ) ;
// printing the decimal value on the console
float f = 5.25412368f ;
System.out.printf( " \n Printing the decimal value : %f \n ", f ) ;
// this formatting is used to specify the width un to which the digits can extend
System.out.printf( " \n Formatting the output to specific width : n = %.4f \n ", f ) ;
// this formatting will print it up to 2 decimal places
System.out.printf( " \n Formatted the output with precision : PI = %.2f \n ", f ) ;
// here number is formatted from right margin and occupies a width of 20 characters
System.out.printf( " \n Formatted to right margin : n = %20.4f \n ", f ) ;
}
}
Output:
Printing the String value : JavaTpoint
Printing the integer value : x = 512
Printing the decimal value : 5.254124
Formatting the output to specific width : n = 5.2541
Formatted the output with precision : PI = 5.25
Formatted to right margin : n = 5.2541

Formatting Using the DecimalFormat Class:

DecimalFormat is used to format decimal numbers.

Example:

import java.text.DecimalFormat ;
// definition of the class
public class FormattedOutput2
{
public static void main( String args[ ] )
{
double x = 123.4567 ;
// printing the number
System.out.printf( " \n The number is : %f \n ", x ) ;
// printing only the numeric part of the floating number
DecimalFormat ft = new DecimalFormat( " #### " ) ;
System.out.println( " \n Without fraction part the number is : " + ft.format( x ) ) ;
// printing the number only upto 2 decimal places
ft = new DecimalFormat( " #.## " ) ;
System.out.println( " \n Formatted number with the specified precision is = " + ft.format( x ) ) ;
// automatically appends zero to the rightmost part of decimal, instead of #, we use digit 0
ft = new DecimalFormat( " #.000000 " ) ;
System.out.println( " \n Appending the zeroes to the right of the number = " + ft.format( x ) ) ;
// automatically appends zero to the leftmost of decimal number instead of #, we use digit 0
ft = new DecimalFormat( " 00000.00 " ) ;
System.out.println( " \n Appending the zeroes to the left of the number = "+ ft.format( x ) ) ;
// formatting money in dollars
double income = 550000.789 ;
ft = new DecimalFormat( " $###,###.## " ) ;
System.out.println( " \n Your Formatted Income in Dollars : " + ft.format( income ) ) ;
}
}
Output:
The number is : 123.456700
Without fraction part the number is : 123
Formatted number with the specified precision is = 123.46
Appending the zeroes to the right of the number = 123.456700
Appending the zeroes to the left of the number = 00123.46
Your Formatted Income in Dollars : $550,000.79

1.17 Control Statements:


Program control statements can be organized into the following categories:
1. Selection or Conditional or Decision Statements
2. Iteration or Looping Statements
3. Jump Statements

Selection or Conditional or Decision Statements:


Decision making structures have one or more conditions to be evaluated or tested, if it is true the
statements getexecuted and optionally, other statements to be executed if the condition is
determined to be false.
Table: Types of Conditional statements

Type Syntax and Explanations Example

if(condition){ int age=20;


1. Simple if

//Statements if(age>18){
}
The Java if statement tests the System.out.print("Age is greater than 18");
condition. It executes if block if }
condition is true.
if(condition){
//Statements int number=13;
if(number%2==0){
2. if-else

}else{
//Statements System.out.println("even number");
} }else{
It executes the if block if condition is System.out.println("odd number");
true otherwise else block is executed.
}
if(condition1){ int age=25,basic=4000,tax = 200;
Statements;
if (age>18) {
3. if-else-if ladder

}else if(condition2){
Statements; System.out.println(“greater”);
} }
... else if (basic > 5000)
else{ sal = basic – tax;
Statements;
else
}
The if-else-if ladder statement executes sal = basic;
one condition from multiple statements.
if (condition){ if Int a=15, b=20, c=18, big;if (a>b){
(condition){ if (a>c) {
4. nested if

Statements; big = a;
} }
} }
You can use one if or else if statement
inside another if or else if statement(s).
switch(expression){
int number=20;
case value1:Statements;
break; switch(number){
5. switch or multiway

case value2:Statements; case 10: System.out.println("10");break;


break; case 20: System.out.println("20");break;
...... case 30: System.out.println("30");break;
default: default:
//code to be executed if all cases are System.out.println("Not in 10,
not matched
20 or 30");
} }
The Java switch statement executes one
statement from multiple conditions.
Iteration Statements:
A loop statement allows us to execute a statement or group of statements multiple times.
Table: Types of Iteration Statements
Type Syntax and Explanations Example

while(condition){ int i=1;


Statements; while(i<=10){
1. while

} System.out.println(i);i++;
Repeats a statement or group of statements while
}
a given condition is true. It tests the condition
Output: 1 2 3 4 5 6 7 8 9 10
before executing the loop body.

do{ int i=1;do{


Statements; System.out.println(i);i++;
2. do-while

}while(condition); }while(i<=10);
Like a while statement, except that it tests the Output: 1 2 3 4 5 6 7 8 9 10
condition at the end of the loop body.

for(initialization;condition;incr/decr) for(int i=1;i<=10;i++){


{ System.out.println(i);
3. for loop

Statements; }
}
Output: 1 2
Execute a sequence of statements multiple times
and 345678

abbreviates the code that manages the loop 9 10


variable.
for(type var : array){ Statements; int arr[]={12,23,44,56,78};
}
4. Enhanced for loop

for(int i:arr){ System.out.println(i);


 for-each loop is used to traverse array or
collection in java. }
 It is easier to use than simple for loop because
we don't need to increment value and use
subscript notation.
 It works on elements basis not index. It returns
element one by one in the defined variable. Output: 12
23 44 56 78
Jump Statements:
Loop control statements change execution from its normal sequence.
Type Syntax and Explanations Example

jump-statement;break; for(int i=1;i<=10;i++){ if(i==5){


 used to break loop or switch statement. break;
}
break

 It breaks the current flow of the program at System.out.println(i);


specified condition.
}
 In case of inner loop, it breaks only inner loop. Output: 1 2 3 4

jump-statement; for(int i=1;i<=10;i++){ if(i==5){


continue; continue;
}
 Used to continue loop.
continue

System.out.println(i);
 It continues the current flow of the program }
and skips the remaining code at specified
condition. Output: 1 2 3 4 6 7 8 9 10
 In case of inner loop, it continues only inner
loop

jump-statement; break for( i=1 ; i<=3 ; i++){ one: {


LABEL;
two: {
break label or break as a form of goto

 The break statement can be followed by a


three: { System.out.println(“i=”+ i ); if( i==1 )
label.
 The presence of a label will transfer control to break one; if( i==2 )
the start of the code identified by the label. break two; if( i==3 )
break three;
}System.out.println(“End Three”);
} System.out.println(“End Two”);
} System.out.println(“End One”);
} // end for
Output:
End One
End Two End One
End Three End Two End One
jump-statement; int a[][]={{1,1,1},{2,2,2},{3,3,3}};

continue label or continue as a form of


continue LABEL;
Outer:
 skips the current iteration of an outer loop
for( int i = 0; i < 3; i++) {
marked with the given label.
for( int j = 0 ; j < 3 ; j++) {
if( i == j) continue Outer;
System.out.println("Element is:"
+ a[i][j]);
}
}
Output:
goto

Element is: 2
Element is: 3
Element is: 3
return value; boolean isOdd( int num ) { if (
num/2 == 0 )
 The return statement exits from the current
method, and control flow returns to where the return false; return true;
method was invoked.
return

}
 The return statement has two forms: one that
returns a value, and one that doesn't.

1.18 Nested Loops:


 One loop can be nested inside of another loop.
 Used to solve a wide variety of programming problems and are an essential part of programming.
Example:

for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print(j+" ");
}
}
1.19 Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax:
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Example:
//Java Program to illustrate how to declare, instantiate, initialize and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output: 10
20
30
40
50

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

Example:
Java Program to illustrate the use of declaration, instantiation and initialization of Java array in a
single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output:
33
3
4
5

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array elements
one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable:array){
//body of the loop
}

Example: Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}

Output:
33
3
4
5

Passing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}

Output: 3

ArrayIndexOutOfBoundsException

The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.

Example: Java Program to demonstrate the case of ArrayIndexOutOfBoundsException in a Java Array.


public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}

Multidimensional Arrays:
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of
other arrays. These are also known as Jagged Arrays. A multidimensional array is created by appending
one set of square brackets ([]) per dimension.
Syntax :
datatype [][] arrayrefvariable;
or
datatype arrayrefvariable[][];
Example: int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Example:

public class multiDimensional {


public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}

Output
279
361
742

1.20 Constructors:
In Java, Constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling the constructor, memory for the object is allocated in the memory.
It is a special type of method that is used to initialize the object. Every time an object is created using
the new() keyword, at least one constructor is called.

Syntax: class Test {


Test() {
// constructor body
}}
Example:
class ABC {
private String name;
// constructor
ABC() {
System.out.println("Constructor Called:");
name = "MCA";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
ABC obj = new ABC();
System.out.println("The name is " + obj.name);
}
}
Output:
Constructor Called:
The name is MCA

Types of Constructor
In Java, constructors can be divided into 4 types:
1. No-Arg Constructor: If a constructor does not accept any parameters, it is known as a no-
argument constructor.
For example, (ABOVE Program)

2. Parameterized Constructor: A Java constructor can also accept one or more parameters.
Such constructors are known as parameterized constructors (constructor with parameters).

Example:
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Output: Java Programming Language
Python Programming Language
C Programming Language

3. Default Constructor: If we do not create any constructor, the Java compiler automatically create a
no-arg constructor during the execution of the program. This constructor is called default constructor.
Example:
class Main {
int a;
boolean b;
public static void main(String[] args) {
// A default constructor is called
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output: Default Value:
a=0
b = false

4. Copy Constructor: In Java, a copy constructor is a special type of constructor that creates an
object using another object of the same Java class. It returns a duplicate copy of an existing object
of the class.

1.21 Methods in Java:


 A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation.
 It is used to achieve the reusability of code. We write a method once and use it many times
 It also provides the easy modification and readability of code, just by adding or removing a
chunk of code.
 The method is executed only when we call or invoke it.

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

Static Method
A method that has static keyword is known as static method. In other words, a method that belongs
to a class rather than an instance of a class is known as a static method. We can also create a static method
by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can access
static data members and also change the value of it. It is used to create an instance method. It is invoked
by using the class name. The best example of a static method is the main() method.

Example:

public class Display


{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}

1.22 Access Modifiers in Java:

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

1.23 this reference:


The “this” is a keyword in Java which is used as a reference to the object of the current class,
with in an instance method or a constructor. Using this you can refer the members of a class such as
constructors, variables and methods.
Using “this” you can −
 Differentiate the instance variables from local variables if they have same names, within a
constructor or a method

Example:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

1.24 Overloading methods and constructors:


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading. Method overloading increases the readability of the program.
Example:

class Adder{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

In Java, we can overload constructors like methods. The constructor overloading can be defined
as the concept of having more than one constructor with different parameters so that every constructor
can perform a different task.
Example:
class Main {
String language;
// constructor with no parameter
Main() {
this.language = "Java";
}
// constructor with a single parameter
Main(String language) {
this.language = language;
}
public void getName() {
System.out.println("Programming Langauage: " + this.language);
}
public static void main(String[] args) {
// call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}
}
Output: Programming Language: Java
Programming Language: Python

Constructor Overloading Method Overloading

Constructors are special methods in Java that Methods are normal functions in Java
are called when an object is created. that can be called on an object or class.
Constructor Overloading Method Overloading

Constructor overloading allows a class to Method overloading allows a class to


have multiple constructors with different have multiple methods with the same
parameter lists. name but different parameter lists.

Constructors are always called when an


Methods are called explicitly by name
object is created, and the appropriate
and can be passed different arguments at
constructor is automatically selected based
each call.
on the arguments used to create the object.

The purpose of constructor overloading is to The purpose of method overloading is to


provide different ways to initialize an object provide different ways to perform a
of a class. specific action in a class.

Methods can have a return type, which


Constructors do not have a return type. can be different for each overloaded
method.

1.25 Recursion:

Recursion in java is a process in which a function/method calls itself continuously. A method in


java that calls itself is called recursive method. This technique provides a way to break complicated
problems down into simple problems which are easier to solve.

Syntax: returntype methodname(){


//code to be executed
methodname();//calling same method
}

Example:
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args) {


System.out.println("Factorial of 5 is: "+factorial(5));
}
}

1.26 Garbage Collection:


Since objects are dynamically allocated by using the new operator, you might be wondering
how such objects are destroyed and their memory released for later reallocation. In some languages, such
as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes
a different approach; it handles deallocation for you automatically. The technique that accomplishes this
is Called garbage collection. It works like this: when no references to an object exist, that object is assumed
to be no longer needed, and the memory occupied by the object can be reclaimed. Furthermore, different
Java run-time implementations will take varying approaches to garbage collection, but for the most part,
you should not have to think about it while writing your programs.

1.27 Exploring string class:


String is a sequence of characters. In java, objects of String are immutable which means a
constant and cannot be changed once created.
Creating a String
There are two ways to create string in Java:
 String literal
String s = “MCA Students”;
 Using new keyword
String s = new String (“MCA students”);

Example:
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Java String class methods

1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, Object... It returns formatted string with given locale.
args)

5 String substring(int beginIndex) It returns substring for given begin index.

6 String substring(int beginIndex, int endIndex) It returns substring for given begin index and end
index.

7 boolean contains(CharSequence s) It returns true or false after matching the sequence


of char value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, Iterable<? It returns a joined string.


extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with the given
object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the specified char
value.

14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the specified
CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It doesn't check case.

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex and limit.

18 String intern() It returns an interned string.


19 int indexOf(int ch) It returns the specified char value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting
with given index.

21 int indexOf(String substring) It returns the specified substring index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring index starting with
given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using specified


locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using specified


locale.

27 String trim() It removes beginning and ending spaces of this


string.

28 static String valueOf(int value) It converts given type into string. It is an overloaded
method.

You might also like