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

Java Module-1

The document provides an overview of Object-Oriented Programming (OOP) concepts and Java programming, detailing key principles such as classes, objects, inheritance, encapsulation, and polymorphism. It also covers the history of Java, its evolution through various versions, and the fundamental data types and structures used in Java programming. Additionally, it discusses Java's operator hierarchy, variable types, and the significance of comments and tokens in Java code.

Uploaded by

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

Java Module-1

The document provides an overview of Object-Oriented Programming (OOP) concepts and Java programming, detailing key principles such as classes, objects, inheritance, encapsulation, and polymorphism. It also covers the history of Java, its evolution through various versions, and the fundamental data types and structures used in Java programming. Additionally, it discusses Java's operator hierarchy, variable types, and the significance of comments and tokens in Java code.

Uploaded by

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

Module-1

OOPS CONCEPTS and JAVA PROGRAMMING:


OOP Concepts: Classes and Objects, Data abstraction, Encapsulation,
Inheritance, Benefits of Inheritance, Polymorphism, Procedural and Object
Oriented Programming paradigm
Procedural language: Any programming language in which the programmer
specifies an explicit sequences of steps to follow to produce a result.

Eg:
Step1: get two input
Step 2: compute two numbers
Step 3: display output
Step 4: stop

Structured Programming: An organized approach to programming involving


the use of three basic control structures – sequence, branch and loop and the use
of two-down concepts to decompose main functions into lower level
components for modular coding purposes.

Characteristics of structured programming:


1. Emphasis on doing things (algorithms)
2. Large programs are divided into smaller programs known as functions
3. Most of the functions share global data.
4. Data move openly around the system from function to function.
5. Functions transform data from one form to another.
6. Employs top-down approach in program design.

Object-Oriented Programming (OOPs): A programming paradigm that


represents concepts as “object” that have data fields and associated
procedures known as methods.
Eg: C++, Java, C#, Perl, Python.

Characteristics of Object Oriented Programming:


1. Emphasis is on data rather than procedure.
2. Programs are divided into objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are ties together in the data
structures.
5. Data is hidden and cannot be accessed by external function.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added whenever necessary
8. Follows bottom-up approach in program design.

Object: An object is a real world element which is an identifiable entity with


some characteristics (attributes) and behavior.
Class: A Class is a blueprint or prototype from which objects are created.
Abstraction: The process of representing essential features without
including the background details or explanation.
Encapsulation: The process that facilitates the bundling of data with the
methods operating on that data.
Polymorphism: The ability for a message (function) or data to be processed
in more than one form.
Add(a,b)
Add(a,b,c)
Inheritance: A mechanism by which one class acquires the properties the
data and operations of another class.
Father has curly hairs son has curly
hairs

Dynamic Binding: It is process of linking procedure call to a specific


sequence of function at runtime or during execution of the program.
Java Programming

Source: James Gosling - Wikipedia

History of Java

Source: https://thetapacademy.com/java-programming-language/
Java Name History
GreenTalk
James Gosling was leading a team named as 'Green' team. Target of this team
was to create a new project which can. Initially C++ was the original choice to
develop the project. James Gosling wanted to enhance C++ to achieve the target
but due to high memory usage, that idea was rejected and team started with a
new language initially named as GreenTalk. The file extension used as .gt. Later
this language was termed as Oak and finally to Java.
Oak
James Gosling renamed language to Oak. There was an Oak tree in front of his
office. James Gosling used this name as Oak represents solidarity and Oak tree
is the national tree of multiple countries like USA, France, Romania etc. But
Oak technologies already had Oak as a trademark and James team had to
brainstrom another title for the language.
Finally Java
Team put multiple names like DNA, Silk, Ruby and Java. Java was finalized by
the team. James Gosling tabled Java title based on type of espresso coffee bean.
Java is an island in Indonesia where new coffee was discovered termed as Java
coffee. As per James Gosling, Java was among the top choice along with Silk.
Finally Java was selected as it was quite unique and represented the essence of
being dynamic,revolutionary and fun to say.
Sun released the first public implementation as Java 1.0 in 1995. It
promised Write Once, Run Anywhere (WORA), providing no-cost run-times on
popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source
software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free
and open-source, aside from a small portion of code to which Sun did not hold
the copyright.
The latest release of the Java Standard Edition is Java SE 21. With the
advancement of Java and its widespread popularity, multiple configurations
were built to suit various types of platforms. For example: J2EE for Enterprise
Applications, J2ME for Mobile Applications.
Java Versions History
Over the period of nearly 30 years, Java has seen many minor and major
versions.

Sr.No. Version Date Description

JDK
1 1995 Initial Draft version
Beta

23
2 JDK 1.0 Jan A stable variant JDK 1.0.2 was termed as JDK 1
1996

19
Major features like JavaBeans, RMI, JDBC, inner
3 JDK 1.1 Feb
classes were added in this release.
1997

8 Dec Swing, JIT Compiler, Java Modules, Collections were


4 JDK 1.2
1998 introduced to JAVA and this release was a great success.

8
HotSpot JVM, JNDI, JPDA, JavaSound and support for
5 JDK 1.3 May
Synthetic proxy classes were added.
2000

Image I/O API to create/read JPEG/PNG image were added.


6 Feb
6 JDK 1.4 Integrated XML parser and XSLT processor (JAXP) and
2002
Preferences API were other important updates.

JDK 1.5 30
Various new features were added to the language like
7 or J2SE Sep
foreach, var-args, generics etc.
5 2004

11
JAVA SE 1. notation was dropped to SE and upgrades done to JAXB
8 Dec
6 2.0, JSR 269 support and JDBC 4.0 support added.
2006

9 JAVA SE 7 Jul Support for dynamic languages added to JVM. Another


7 2011 enhancements included string in switch case, compressed 64
bit pointers etc.

18 Support for functional programming added. Lambda


JAVA SE
10 Mar expressions,streams, default methods, new date-time APIs
8
2014 introduced.

21
JAVA SE Module system introduced which can be applied to JVM
11 Sep
9 platform.
2017

20 Unicode language-tag extensions added. Root certificates,


JAVA SE
12 Mar thread local handshakes, support for heap allocation on
10
2018 alternate memory devices etc were introduced.

Dynamic class-file constants, Epsilon a no-op garbage


JAVA SE 5 Sep
13 collector, local-variable support in lambda parameters, Low-
11 2018
overhead heap profiling support added.

19 Experimental Garbage Collector, Shenandoah: A Low-


JAVA SE
14 Mar Pause-Time Garbage Collector, Microbenchmark Suite,
12
2019 JVM Constants API added.

17
JAVA SE Feature added - Text Blocks (Multiline strings), Enhanced
15 Sep
13 Thread-local handshakes.
2019

17 Feature added - Records, a new class type for modelling,


JAVA SE
16 Mar Pattern Matching for instanceof, Intuitive
14
2020 NullPointerException handling.

15
JAVA SE Feature added - Sealed Classes, Hidden Classes, Foreign
17 Sep
15 Function and Memory API (Incubator).
2020

16
JAVA SE Feature added as preview - Records, Pattern Matching for
18 Mar
16 switch, Unix Domain Socket Channel (Incubator) etc.
2021
14 Feature added as finalized - Sealed Classes, Pattern
JAVA SE
19 Sep Matching for instanceof, Strong encapsulation of JDK
17
2021 internals by default. New macOS rendering pipeline etc.

22 Feature added - UTF-8 by Default, Code Snippets in Java


JAVA SE
20 Mar API Documentation, Vector API (Third incubator), Foreign
18
2022 Function, Memory API (Second Incubator) etc.

20
JAVA SE Feature added - Record pattern, Vector API (Fourth
21 Sep
19 incubator), Structured Concurrency (Incubator) etc.
2022

Feature added - Scoped Values (Incubator), Record Patterns


21
JAVA SE (Second Preview), Pattern Matching for switch (Fourth
22 Mar
20 Preview), Foreign Function & Memory API (Second
2023
Preview) etc.

19 Feature added - String Templates (Preview), Sequenced


JAVA SE
22 Sep Collections, Generational ZGC, Record Patterns, Pattern
21
2023 Matching for switch etc.

In Java, every application begins with a class definition. In the


program, HelloWorld is the name of the class, and the class definition is:

Comments:
 Single-line comments: //
 Multiline comments: /* */
 Documentation comments
The documentation comments are used for writing the documentation of the source code.
The documentation comments start with a forward slash followed by the two asterisks
(/**), end with an asterisk followed by a backward slash (*/), and all lines between the
start and end must start with an asterisk (*).

 The documentation comments are understood by the Javadoc tool and can be used to
create HTML-based documentation.
Java Tokens: it is a smallest individual element in the program
Java tokens has five types: Reserved keywords, identifiers, literals, operators
and separators
Character set: Unicode character set [A-Z, a-z, 0-9 and special character which
are available in keyboard]
Keyword: 50 keywords
Identifiers:
Literals: constant values to be stored in variable
Integral literal, floating point literal, character literal, string and Boolean
‘A’ character, it require 1 byte of memory
“Apple” string it require no of character + 1 byte of memory (i.e 5 character + 1
byte, last bit is used for null character which represent end of string.)
Operators:
Arithmetic: +, -, *, /, %
Relational: <,<=,>,>=,!=,==
Logical: && (AND), || (OR is a pipe symbole), !( not)
Assignment: =
Increment or decrement: ++, --
Conditional: ? : ( exp1?exp2: exp3)
(marks>35? “Pass”: “Try again”;)
Bitwise : &, |, ^ (Exclusive OR), ~ (one complement), << (shift left), >>
(Shift right), >>> (Shift right with zero fill)
Special operators: to indicate a group of code, [] arrays, () functions

We compile the program, we get bytecode.Java interpreter reads bytecode and


translate into machine code
Java Virtual Machine (JVM)
Java program-> Java Compiler->Virtual Machine -> java interpreter -> Machine
Sourcecode byte code

Data types: The data type tells the compiler about the type of data to be stored
and the required memory. To store and manipulate different types of data, all
variables must have specified data types.
 Primitive Data Types
 Reference/Object Data Types

Primitive data types are predefined by the language and named by a keyword.
There are eight primitive data types supported by Java
Type Siz Range Min Max
e in
bits
Byte 8 -128 to -128 127
127
Short 16 -32,768 -32768 32767
to
32,767
Int 32 -231 to -2147483648 2147483647
231-1
Long 64 -263 to - 9223372036854775807
263-1 922337203685477580
8
Float 32 1.4e-045 1.4E-45 3.4028235E38
to
3.4e+03 Sufficient for storing 6 to
8 7 decimal digits
Char 16 0 to
65,535
Boolea 1 True or
n false
Double 8 4.9E-324 1.7976931348623157E30
8
Sufficient for storing 15
decimal digits

Java Reference/Object Data Type


The reference data types are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.

Variables : Variables are containers for storing data values


Constants
Scope and life time of variables
Instance Variables
A variable which is declared inside a class and outside all the methods and
blocks is an instance variable. The general scope of an instance variable is
throughout the class except in static methods. The lifetime of an instance
variable is until the object stays in memory.
Class Variables
A variable which is declared inside a class, outside all the blocks and is marked
static is known as a class variable. The general scope of a class variable is
throughout the class and the lifetime of a class variable is until the end of the
program or as long as the class is loaded in memory.
Local Variables
All other variables which are not instance and class variables are treated as local
variables including the parameters in a method. Scope of a local variable is
within the block in which it is declared and the lifetime of a local variable is
until the control leaves the block in which it is declared.

Operator Hierarchy
The operator precedence represents how two expressions are bind together. In
an expression, it determines the grouping of operators with operands and
decides how an expression will evaluate.
While solving an expression two things must be kept in mind the first is
a precedence and the second is associativity.

Java Operator Precedence Table


The following table describes the precedence and associativity of operators
used in Java.

Precedence Operator Type Associativity

15 () Parentheses Left to Right


[] Array subscript
· Member selection

14 ++ Unary post-increment Right to left


-- Unary post-decrement

13 ++ Unary pre-increment Right to left


-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast

12 * Multiplication Left to right


/ Division
% Modulus

11 + Addition Left to right


- Subtraction

10 << Bitwise left shift Left to right


>> Bitwise right shift with sign
>>> extension
Bitwise right shift with zero
extension

9 < Relational less than Left to right


<= Relational less than or equal
> Relational greater than
>= Relational greater than or
instanceof equal
Type comparison (objects
only)

8 == Relational is equal to Left to right


!= Relational is not equal to

7 & Bitwise AND Left to right

6 ^ Bitwise exclusive OR Left to right

5 | Bitwise inclusive OR Left to right

4 && Logical AND Left to right

3 || Logical OR Left to right


2 ?: Ternary conditional Right to left

1 = Assignment Right to left


+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Expressions
Type conversions and Casting
Enumerated Types
Control Flow Statements
Jump Statements
Arrays
Input and Output
Java brings various Streams with its I/O package that helps the user to perform all the input-
output operations. These streams support all the types of objects, data-types, characters, files
etc to fully execute the I/O operations.

3 standard or default streams that Java has to provide which are also most
common in use:
1. System.in: This is the standard input stream that is used to read characters
from the keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the
result of a program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
 print(): This method in Java is used to display a text on the console.
This text is passed as the parameter to this method in the form of
String. This method prints the text on the console and the cursor
remains at the end of the text at the console. The next printing takes
place from just here.
Syntax:
System.out.print(parameter);
println(): This method in Java is also used to display a text on the console. It
prints the text on the console and the cursor moves to the start of the next line at
the console. The next printing takes place from the next line.
Syntax:
System.out.println(parameter);
printf(): This is the easiest of all methods as this is similar to printf in C. Note
that System.out.print() and System.out.println() take a single argument, but
printf() may take multiple arguments. This is used to format the output in Java.
1. System.err: This is the standard error stream that is used to output
all the error data that a program might throw, on a computer screen
or any standard output device.
This stream also uses all the 3 above-mentioned functions to output the
error data:
 print()
 println()
 printf()
Types of Streams:
 Depending on the type of operations, streams can be divided into two
primary classes:
1. Input Stream: These streams are used to read data that must
be taken as an input from a source array or file or any
peripheral device. For eg., FileInputStream,
BufferedInputStream, ByteArrayInputStream etc.

2. Output Stream: These streams are used to write data as


outputs into an array or file or any output peripheral device.
For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.

 Depending on the types of file, Streams can be divided into two


primary classes which can be further divided into other classes as can
be seen through the diagram below followed by the explanations.

1. ByteStream: This is used to process data byte by byte (8 bits).


Though it has many classes, the FileInputStream and the
FileOutputStream are the most popular ones. The
FileInputStream is used to read from the source and
FileOutputStream is used to write to the destination. Here is
the list of various ByteStream Classes:
Stream class Description

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

PrintStream This contains the most used print() and println() method

BufferedOutputStrea
This is used for Buffered Output Stream.
m

DataOutputStream This contains method for writing java standard data types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.


Formatting Output
Java String Format Specifiers

Format Data Type Output


Specifier

%a floating point ( except Returns Hex output of floating-point


BigDecima l) number.

%b Any type " true " if non-null, " false " if null

%c Character Unicode character

%d integer ( incl. byte, short, Decimal Integer


int, long, bigint )

%e floating point Decimal number in scientific notation

%f floating point Decimal number

%g floating point Decimal number, possibly in scientific


notation depending on the precision and
value.

%h any type Hex String of value from hashCode( )


method.

%n None Platform-specific line separator.

%o integer ( incl. byte, short, Octal number


int, long, bigint )

%s any type String value

%t Date/Time ( incl. long, %t is the prefix for Date/Time


Calendar, Date and conversions. More formatting flags are
TemporalAccessor ) needed after this. See Date/Time
conversion below.

%x integer ( incl. byte, short, Hex string.


int, long, bigint )

Constructors
In Java, a 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.

// Java Program to demonstrate Constructor


import java.io.*;
class ConstructorEx {
// Constructor
ConstructorEx()
{
super();
System.out.println("Constructor Called");
}
// main function
public static void main(String[] args)
{
ConstructorEx ce= new ConstructorEx();
}
}

Note: It is not necessary to write a constructor for a class. It is because the java compiler
creates a default constructor (constructor with no arguments) if your class doesn’t have any.
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-
class or an overloaded constructor), if you don’t type in the call to super in your constructor
the compiler will provide you with a non-argument call to super at the first line of your code,
the super constructor must be called to create an object:
If you think your class is not a subclass it actually is, every class in Java is the subclass of a
class object even if you don’t say extends object in your class definition.

When Java Constructor is called?


Each time an object is created using a new() keyword, at least one constructor (it could be the
default constructor) is invoked to assign initial values to the data members of the same class.
Rules for writing constructors are as follows:
 The constructor(s) of a class must have the same name as the class name in which it
resides.
 A constructor in Java can not be abstract, final, static, or Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.
Types of Constructors in Java
 Default Constructor
 Parameterized Constructor
 Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the compiler does
not create a default constructor. It is taken out. It is being overloaded and called a
parameterized constructor. The default constructor changed into the parameterized
constructor. But Parameterized constructor can’t change the default constructor. The default
constructor can be implicit or explicit. If we don’t define explicitly, we get an implicit default
constructor. If we manually write a constructor, the implicit one is overridded.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.
// Java Program for Parameterized Constructor
import java.io.*;
class ParaConstructor {
// data members of the class.
String name;
int id;
ParaConstructor(String name, int id)
{
this.name = name;
this.id = id;
}
}
class Navkis {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
ParaConstructor PC = new ParaConstructor("Raj", 24);
System.out.println("Name :" + PC.name
+ " and Id :" + PC.id);
}
}

3. Copy Constructor in Java


Unlike other constructors copy constructor is passed with another object which
copies the data available from the passed object to the newly created object.
// Java Program for Copy Constructor
import java.io.*;

class Ge {
// data members of the class.
String name;
int id;

// Parameterized Constructor
Ge(String name, int id)
{
this.name = name;
this.id = id;
}

// Copy Constructor
Ge(Ge obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class CopyConstructor{
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Ge ge1 = new Ge("Raj", 24);
System.out.println("Name :" + ge1.name + " and Id :" + ge1.id);

System.out.println();

// This would invoke the copy constructor.


Ge ge2 = new Ge(ge1);
System.out.println("Copy Constructor used Second Object");
System.out.println("Name :" + ge2.name + " and Id :" + ge2.id);
}
}

Methods
Parameter passing
Static Field and Methods
The static keyword is used to construct methods that will exist regardless of whether or not
any instances of the class are generated. Any method that uses the static keyword is referred
to as a static method.
Features of static method:
 A static method in Java is a method that is part of a class rather than an instance of
that class.
 Every instance of a class has access to the method.
 Static methods have access to class variables (static variables) without using the
class’s object (instance).
 Only static data may be accessed by a static method. It is unable to access data that is
not static (instance variables).
 In both static and non-static methods, static methods can be accessed directly.
Syntax to declare the static method:
Access_modifier static void methodName()
{
// Method body.
}
The name of the class can be used to invoke or access static methods.
Syntax to call a static method:
className.methodName();

Difference Between the static method and instance method

Instance Methods Static Methods

It requires an object of the class. It doesn’t require an object of the class.

It can access only the static attribute of a


It can access all attributes of a class.
class.

The methods can be accessed only using The method is only accessed by class
object reference. name.

Syntax: Objref.methodname() Syntax: className.methodname()

It’s an example of pass-by-value It is an example of pass-by-reference


programming. programming.

Access control
This reference
Overloading methods and constructors
Recursion
Garbage collection
Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short. When Java programs run on the JVM, objects are created on the heap,
which is a portion of memory dedicated to the program. Eventually, some objects will no
longer be needed. The garbage collector finds these unused objects and deletes them to free
up memory.

Exploring String Class


Java String class methods
The java.lang.String class provides many useful methods to perform
operations on sequence of char values.

No. Method Description

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, It returns a formatted string.


Object... args)

4 static String format(Locale l, String It returns formatted string with


format, Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.

6 String substring(int beginIndex, int It returns substring for given


endIndex) 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 It returns a joined string.


delimiter, CharSequence... elements)

9 static String join(CharSequence It returns a joined string.


delimiter, Iterable<? 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, It replaces all occurrences of the


CharSequence new) specified CharSequence.

15 static String equalsIgnoreCase(String It compares another string. It


another) 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 It returns the specified substring


fromIndex) 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.
Lab Program

You might also like