NEW SYLLABUS
CBCS PATTERN
Core Java
Dr. Ms. Manisha Bharambe
Mrs. Manisha Suryawanshi
Kamil Ajmal Khan
OMIBAL!
eatin5
gpruncn Si 4 Boon oF
Core Java
For B.B.A.(C.A) : Semester - V
[Course Code CA-503 : Credits-03]
SES
As Per New Syllabus, Effective from June 2021
Dr. Ms. Manisha Bharambe
M.Sc. (Comp. Sci.), M.Phil, Ph.D (Comp. Sci.)
\ice Principal and BCA Coordinator
MES Abasaheb Garviare College, Pune 4
Mrs. Manisha Suryawanshi
M.CS., MPhil. (CS), M-B.A. (HR)
Asst. Prof., Placement Co-ordinator
Modern College of Arts, Science and Commerce
(Autonomous), Pune 5
Mr. Kamil Ajmal Khan
Mise. Computer Science
Asst. Prof. Computer Science Department
‘Abeda Inamdar Senior College, Pune
Price = 360.00
NIRALI
DOME
N4959]CORE JAVA ISBN 978-93-5451-305-3
First Edition + September 2022
e Authors
The tet of this publication, of any part thereat should not be reproduce or transmitted in any form oF stomd in any
‘compute storage system or device for dstrbution including photocopy, recarng, taping or information retrieval sytem or
repraductd on any clic tape, perforated media or ther information storage device etc. without the writen permission of
‘uthas wth whorn the rights ae reserved Breach ofthis canton fable for lege! action,
Every effort has bean made to avoid eros or omissions in tis publication. In site ofthis erers may have creo n. Any
mistake, evr or dscrepancy So nated and shall be brought to cur netic shall be taken care af in the nest edition I s notified
‘that neither the publisher na the authors or slr shall be responsible for any damage or loss of action to any one of any kind, in
any mane, theretrom. The reader must cass check all the fats end contents with ariginal Goverment natfeation or
publications
Published sy : Polyplate Printed By :
NIRALI PRAKASHAN ‘YOGIRAJ PRINTERS AND BINDERS
‘Abhyudaya Pragati, 1312, Shiva Nagar, ‘Survey No, 10/14, Ghule Industial Estate
(Off JIM, Foe, Pune — 411005 Nanded Gaon Road
Tel - (020 25512336/37/39 Nanded, Pune- 411081
Email: nkalipune@pragationiinecom
Seren keine
PUNE
Nirali Prakeshan Nirali Prakashan
(For orders outside Pune) (For orders within Pune)
S.No, 28/27, Dhayari Nate Road, Near Asian College 119, Bushwar Peth Jogeshwari Mandi Lare
Pune 411081, Maharashtra Pune 411002, Maharashtra
“Tel (020) 24680204; Mobile: 9557703143, Tel: (020) 2445 2044; Mobile: 9657703145
Email: bookorder@pragationinecom Email:
[email protected]
MUMBAI
Nirali Prakeshan
Rasdhara Co-op. Hig. Society Ltd, 0’ Wing Ground Floor, 385 SVP. Road
‘Grgaum, Mumbai 400004, Maharastera
Mobile: 7945821020, Tel: (022) 2385 6339 /2386 9976
Enail:riralimumbai@pragationline com
Mercere
DELHI BENGALURU NAGPUR
Nirali Prakashan Nirali Prakashan Nirali Prakashan
Room No.2 Ground Floor __| NeitriGraund Fiver, Jaya Apartments, | Above Maratha Mend, Shop No.3
4575/15 Omar Tower, Agarwal Road | No. 99, 6" Cross 6” Main, Fist Floor, Rani Jhansi Seuare,
Dara Ganj, New Del 110002 | Meleswaram, Bengalurs 560008 | Sitabuldi Nagpur 440012 (WAH)
Mobie:9555778814/9818561840 | Kamataka: Mob 9686821074 Tel: 0712) 254.7128
Email: dehi@niraibookscom | Email: bengaluru@niraibeckscom | Email: nagpur@niaibeoks com
KOLHAPUR JALGAON SOLAPUR
Nirali Prakashan Nirali Prakashan Nirali Prakashan
New Mahadve Road, ede Plaza, | 34, v-V.Golani Market, Navi eth, | R-258/2, venti Naga, Neat Golden
{Floor Opp DBI Bank Jalgaon 425001. Maharestre ‘Gate, Pune Naka Chowk
Kolhapur 416 012 Maharashtra Tel: 0257) 222 0395, Solapur 413001, Maharastra
Mob : 9850046155 Mob : 94234 91860 Mobile 9890818687
Email: kolhapur@nicalbookscom | Emall:jalgeon@niralinockscom | Email: solapur@niralivockscom
A ce
eee
eeePreface...
We take an opportunity to present this book entitled as “Core Java" to the students of
Fifth Semester - B.B.A.(C.A). The object of this book is to present the subject matter ina most
concise and simple manner. The book is written strictly according to the New Syllabus
(CBCS Pattern).
The book covers theory of Java Fundamentals, Classes, Objects and Methods, Inheritance,
Package and Collection, File and Exception Handling, Applet, AWT, Event and Swing
Programming.
The book has its own unique features. It brings out the subject in a very simple and lucid
manner for easy and comprehensive understanding of the basic concepts, its intricacies,
procedures and practices. This book will help the readers to have a broader view on Core
Jaya. The language used in this book is easy and vill help students to improve their
vocabulary of Technical terms and understand the matter ina better and happier way.
A special words of thank to Shri. Dineshbhai Furia, Mr. Jignesh Furia for showing full faith
in us to write this text book. We also thank to Mr. Akbar Shaikh of M/s Nirali Prakashan for
their excellent co-operation,
We also thank Mr. Akbar Shaikh, Ms. Chaitali Takale, Mr. Ravindra Walodare, Mr. Sachin
Shinde, Mr. Ashok Bodke, Mr. Moshin Sayyed and Mr. Nitin Thorat.
Although every care has been taken to check mistakes and misprints, any errors,
‘omission and suggestions from teachers and students for the improvement of this text book
shall be most welcome,
Authors.Syllabus ...
1.
3.
Java Fundamentals [Lectures 8]
1
12
13
14
15
16
17
18
Introduction to Java
Basics of Java: Data Types, Variable, Expression, Operators, Constant
Structure of Java Program
Execution Process of Java Program
JDK Tools
Command Line Arguments
Array and String
17.1 Single Array and Multidimensional Array
17.2. String, String Butfer
Built In Packages and Classes
18.1 java.util: Scanner, Date, Math etc
182 javalang
Classes, Objects and Methods [Lectures 8]
21
22
23
24
Class and Object
Object Reference
Constructor: Constructor Overloading
Method: Method Overloading, Recursion, Passing and Returning Object Form
Method
25 Nev Operator, this and static keyword, finalize Method
26 Nested Class, Inner Class and Anonymous Inner Class
Inheritance, Package and Collection Lectures 10]
3.1 Overview of Inheritance
3.2. Inheritance in Constructor
33 Inheriting Data Members and Methods
34 Multilevel Inheritance - Method Overriding Handle Multilevel Constructors
35 Use of Super and Final Keyword.
3.6 Interface
3.7 Creation and Implementation of an Interface, Interface Reference
38 Interface Inheritance
39 Dynamic Method Dispatch
3.10 Abstract Class
3.11 Comparison between Abstract Class and Interface
3.12 Access Control
3.13. Packages
3.13.1 Packages Concept
3.132 Creating User Defined Packages
3.13.3 Java Built Inpackages
3.134 Import Statement, Static Import314 Collection
3.14.1 Collection Framework.
3.142 Interfaces: Collection, List, Set
3.143 Navigation: Enumeration, Iterator, ListIterator
3.144 Classes: Linkedlist, ArrayList, Vector, HashSet,
File and Exception Handling [Lectures 8]
Exception
41 Exception and Error
42 Use of try, catch, throw, throws and finally
43 Built in Exception
44 Custom exception
45 Throwable Class.
File Handling
46 Overview of Different Stream (Byte Stream, Character stream)
47 Readers and Writers class
43 File Class
49 File Input Stream, File Output Stream
410 Input Stream Reader and Output Strearn Writer
Class
ALL FileReader and FileWrler Class
412 Buffered Reader Class
Applet, AWT, Event and Swing Programming [Lectures 14]
Applet
51 Introduction
52 Types Applet
53. Applet Lifecycle
5.3.1 Creating Applet
53.2 Applet Tag
54 Applet Classes
541 Color
54.2 Graphics
543 Font
AWT
55 Components and container used in AWT
56 Layout Managers
57 Listeners and Adapter Classes
52 Event Delegation Model
Swing
59. Introduction to Swing Component and Container Classes
5.10 Exploring Swing Controls - JLabel and Image Icon, JText Field, The Swing Buttons
JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed Pane, JScroll Pane,
JList, JTable, JComboBox, Swing Menus, Dialogs, IFileOpen, JColorChooser
-Contents ...
4. Java Fundamentals
2. Classes, Objects and Methods
3. Inheritance, Package and Collection
and Exception Handling
5. Applet, AWT, Event and Swing Programming
Bibliography
41 - 1.50
2A = 2.32
34 - 3.72
44 - 4.40
5A - 5.88
BA-BAJava Fundamentals
Learning Objectives...
‘To understand Basic Concepts of Java.
To learn Structure of Java
To study JDK Tools.
To study Command Line Arguments,
To learn about Array and String.
To study Built In Packages and Classes.
asa m
B® wrropucine java
‘+ Java is a class-based, object-oriented, simple programming language. Java makes
writing, compiling, and debugging programming easy. It helps to create reusable
code and modular programs.
+ Java is used for Mobile applications, Desktop applications, Web applications, Web
servers and Application servers, Games, Database connection, etc.
+ Java works on different platforms like Windows, Mac, Linux, Raspberry Pi, etc.
‘+ Java is related to C++, whichis a direct descendant of C. Much of the character of Java
is inherited from these twro languages. From C, Java derives its syntax. Many of Java's
object-oriented features were influenced by C++.
+ Itisa general-purpose programming language, intended to let application developers
write once, run anywhere, Meaning that compiled Java code can run on all platforms
that support Java without the need for recompilation. Java applications are typically
compiled to bytecode that can run on any Java virtual machine (JVM).
+ Java enables computer programmers to write computer instructions using English
based commands, instead of having to write in numeric codes.
+ Like English language, Java has a set of rules (syntax) that determine how the
instructions are written. Once, a program has been written, the high-level
instructions are translated into numeric codes that computers can understand and
execute,
(ayCore Java [BBA(CA): Sem. VI 42 Java Fundamentals
cE History of Java
Java was developed at Sun Microsystems (which has since been acquired by Oracle) in
1991, by a team of James Gosling, Patrick Naughton, Chris Wrath, Ed Frank and Mike
Sheridan as its members. The language was initially called Oak. It was later termed as,
Java,
* Between the initial implementation of Oak in the fall of 1992 and the public
announcement of Java in the spring of 1995, many more people contributed to the
design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne,
Frank Yellin, and Tim Lind holm were key contributors to the maturing of the original
prototype
+ Java is a general-purpose, Object-Oriented Programming (OOP) language. James
Gosling is called the father of Java Programming.
‘+ Java is an Object-Oriented Programming language means Java enables us not only to
organize our program code into logical unit called objects but also to take advantage
of encapsulation, inheritance, polymorphism and soon.
+ As of March 2021, the latest version is Java 16, with Java 11, a currently supported
long-term support (LTS) version, released on September 25, 2018. Oracle released the
last zero-cost public update for the legacy version Java 8 LTS in January 2019 for
commercial use, although itwill otherwise still support Java 8 with public updates for
personal use indefinitely. Other vendors have begun to offer zero-cost builds of
OpenjDK 8 and 11 that are still receiving security and other upgrades.
+ Oracle (and others) highly recommend uninstalling outdated versions of Java because
of serious risks due to unresolved security issues. Since Java 9, 10, 12, 13, 14, and 15
are no longer supported, Oracle advises its users to immediately transition to the
latest version (currently Java 16) or an LTS release.
* An application is a type of software that allows user to perform specific task. Sun
Microsystems Inc. has divided Java into following parts
1. Java SE (Java Standard Edition): It contains basic core Java classes and used to
develop standard applets and applications.
2. J2EE (Java Enterprise Edition): It contains classes that are beyond Java SE and used
to providing business solutions on a network.
3. J2ME (lava Micro Edition): Java ME is for developers who develop code for portable
devices like a PDA, a cellular phone and so on.
FRE] Features of Java
+ Following are list of buzzwords:
1, Simple: Java is a simple language. There are various concepts that makes the Java
as a simple language. Java is designed to be easy to learn. Programs in Java are
easy to write and debug because Java does not use the pointers, preprocessor
header files, operator overloading ete.
2. Secure: Java is aimed tobe used in networked or distributed environments. Java
does not allocate direct pointer to memory, this makes it impossible to
accidentally reference memory that belongs to other program.Core Java [BBA(CA): Sem. VI 43 Java Fundamentals
3.
4.
10.
11.
Portable: Being architectural-neutral and having no implementation dependent
aspects of the specification makes Java portable. Java code is portable. It was an
important design goal of Java that it be portable so that as new architectures (due
to hardware, operating system, or both) are developed, the Java environment
could be ported to them.
Object-oriented: Java is a truly object oriented language. Almost everything in
java is an object. Java has a wide variety of classes. These classes are organized in
various packages. We can use them in our programs while implementing
inheritance. The object model in java is simple and easy to extend.
Robust: Java is a robust language because it provides many safeguards to ensure
reliable code. Java does not allow pointer which avoids security problem. There is
no concept of reference variable. This eliminates the possibility of overwriting
memory and corrupting data, Automatic garbage collection eliminates memory
leaks.
Multithreaded: Java was designed to meet the real-world requirement of creating
interactive, networked programs. To accomplish this, Java supports
multithreaded programming, which allows you to write programs that do many
things simultaneously. The Java run-time system comes with an elegant yet
sophisticated solution for multi-process synchronization that enables you to
construct smoothly running interactive systems.
Architecture-neutral: A central issue for the Java designers was that of code
longevity and portability. One of the main problems facing programmers is that
no guarantee exists that if you write a program today, it will run tomorrow even
on the same machine. Operating system upgrades, processor upgrades, and
changes in core system resources can all combine to make a program
malfunction. Their goal was "write once; run anywhere, anytime, forever.” To a
great extent, this goal wes accomplished.
Interpreted: As described earlier, Java enables the creation of cross-platform
programs by compiling into an intermediate representation called Java bytecode.
‘Most previous attempts at cross-platform solutions have done so at the expense of
performance.
High Performance: The Java bytecode was carefully designed so that it would be
easy to translate directly into native machine co¢e for very high performance by
using a just-in-time compiler.
Distributed: Java facilitates the building of distributed application by a collection
of classes for use in networked applications. Java is designed for the distributed
environment of the Internet,
Dynamic: Java language is capable of dynamically linking in new class libraries,
methods and objects. Because Java is interpreted, Java is an extremely dynamic
language, at runtime, the Java environment can extends itself by linking in
classes that may be located on remote servers on a network, for example, the
Internet.Core Java [BBA(CA): Sem. VI a Java Fundamentals
BASICS OF JAVA - DATA TYPES, VARIABLE, EXPRESSION,
OPERATORS, CONSTANT
Data Types
+ A computer has to process various types of data. Data type is a term that refers to the
kind of data used in a program. Every programming language comes with a set of
data types ready to use.
* Java is a strongly typed language and this means that every variable and every
expression has a data type known at compile time.
1. The Primitive Types:
+ Various primitive data types are listed below:
(i) byte:
© Byte data type is an &-bit signed two's complement integer.
© Rangeis~128 to127.
© Default valueis 0.
© Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an int.
© Example: byte a = 100, byteb =-50
(ii) short:
© Short data type is a 45-bit signed two's complement integer.
© Minimum value is -32,768 and maximum value is 32,767.
© Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an int.
© Default valueis 0.
© Example: shorts = 10000, short
(ii) int:
© int data type is a 32-bit signed two's complement integer.
© Range is - 2,147,483,648.. to 2,147,483,647.
© intis generally used as the default data type for integral values unless there is
aconcern about memory.
© The default value is 0
© Example: int a = 100000, intb = -200000
(iv) long:
© long data type is a 64-bit signed two's complement integer.
© Range is -9,223,372,036,854,775,808... to 9,223,372,036,854,775,807.
© This type is used when a wider range than int is needed.
© Default values OL.
© Example: long a= 1000001, int b
20000
2000001.Core Java [BBA(CA): Sem. VI 4s Java Fundamentals
(v) float:
© float data type is a single-precision 32-bit IEEE 754 floating point.
© float is mainly used to save memory in large arrays of floating point numbers.
© default value is 0.0f.
© float data type is never used for precise valuessuch as currency.
© Example: float f1=234.5f
(vi) double:
© double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values,
generally the default choice.
© Double data type should never be used for precise values such as currency.
© Default valueis 0.04.
© Example: double di = 123.4
(vii) boolean:
© boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
© Default value is false
© Example: boolean one = true
(viii) cha
© char data types a single 16-bit unicode character.
© Minimum value is '\u0000' (or 0).
© Maximum value is \uffff (or 65,535 inclusive),
© Char data type is used to store any character.
© Example: char lettera,
2, Reference Data Types:
‘+ Reference data types are made by the logical grouping of primitive data types.
‘+ These are called reference data types because they contain the address of a value
rather than the value itself.
+ _Arrays, classes, enum etc., are the example of reference data type.
Variables
+ Variables are the identifier of the memory location, which used to save data
temporarily for later use in the program. During execution of a program, values can
bestored in a variable, and the stored value can be changed.
+ While naming Java variables we have following naming rules.
1. Variable names are case-sensitive.
2. Variable name can be an unlimited-length sequence of Unicode letters and digits.Core Java [BBA(CA): Sem. VI 16 Java Fundamentals
3. Variable name must be
underscore character
jin with either a letter or the dollar sign "6", or the
‘No white space is permitted in variable names.
Variable name must not be a keyword or reserved word.
Do not begin with a digit,
7,_Aname can be of any realistic length.
aoe
Program 1.1: Program for variables.
public class AddTwoNunbers
t
public static void main(String args{])
{
int nund = 50;
int num2 = 155
int sum;
sum = numi + numa;
System.out.printIn("Sum of Numbers: “+sun);
}
}
Output:
Sun of Numbers: 65
Expression
‘+ Expressions are essential building blocks of any Java program, usually created to
produce a new value, although sometimes an expression assigns a value to a variable.
‘+ Anexpression is a construct made up of variables, operators, and method invocations,
which are constructed according to the syntax of the language that evaluates to a
single value.
Expression evaluation in Java is based upon the following concepts:
1. Type conversion: It has two types based on how the conversion is performed:
(i) Implicit conversion: It is also known as automatic conversion. This type of
conversion is performed automatically by Java due to performance reasons.
Implicit conversion is not performed at all times. For example, Java will
automatically convert a value of byte into int type in expressions since they are
both compatible and int is larger than byte type.
(ii) Explicit conversion: It is also known as Type Casting. There may be situations
where you want to convert a value having a type of size less than the destination
type size. In such cases Java will not help you. You have do it on your own
explicitly. That is why this type of conversion is known as explicit conversion or
casting as the programmer does this manually.Core Java [BBA(CA): Sem. VI a7 Java Fundamentals
Example:
int
85
byte b = (int) as //integer value to be converted into a byte type
‘Type promotion rules of Java for expressions are listed below:
© Allchar, short and byte values are automatically promoted to int type.
© If at least one operand in an expression is a long type, then the entire
expression will be promoted to long.
© If at least one operand in an expression is a float type, then the entire
expression will be promoted to float.
© If at least one operand in an expression is a double type, then the entire
expression willbe promoted to double.
2. Operator Precedence: Operator precedence determines the order in which the
operators in an expression are evaluated.
Table 1.1: Operator Precedence
Operators Associativity
equality left toright
bitwise AND & left to right
bitwise exclusiveOR | * left to right
bitwise inclusiveOR | | left to right
Program 1.2: Program for operator precedence.
class Precedence
t
public static void main(String] ares)
{
int a
18, b= 5,
result = a-t+c~44b;
systen.out.printIn(result);
1, result;
}
Output: 2
‘+ The operator precedence of prefix + is higher than that of - subtraction operator.
3. Associativity of Operators in Java: If an expression has two operators with similar
precedence, the expression is evaluated according to its associativity (either left to
right, orright toleft).
Example:
(i) dzasbte
Since + operator is left associative therefore a+b will solve first and then the
result will be added to c.Core Java [BBA(CA): Sem. VI 1s Java Fundamentals
(il) d=arb*e
Since exponent operator is right associative therefore bc will soved first and
then a* result of b*c
FEZ] operators
‘+ Operators in Java can be classified into 6 types:
1. Unary operators:
+ Unary plus operator; indicates positive value,
= Unary minus operator; negates an expression.
++ Increment operator; increments a value by 1.
-- Decrement operator; decrements a value by 1.
1 Logical complement operator; inverts the value of a Boolean.
Program 1.3: Program for unary operator.
public class Unary
{
public static vold main(string argst])
{
Ant 2920;
System. out .printIn(a++);
system. out.printin(++a) ;
System.out.printin(a--)}
System.out. printIn(--a);
Output:
28
2
2
26
2, Arithmetic operators:
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
Division operator
Remainder operator
RsCore Java [BBA(CA): Sem. VI 19 Java Fundamentals
Program 1.4: Program for Arithmetic operator.
public class Arithmetic
{
public static void main(String args)
{
int
int
System. out.printIn(a+b) ;
System. out .printIn(a-b) ;
System. out .printin(a"b) ;
System. out .print1n(a/b) ;
3
+
output:
30
10
200
2
3. Bitwise and Bit Shift Operators
~~ Unary bitwise complement
<< Signed eft shift
>> Signed right shift
>>> Unsigned right shift
& — Bitwise AND
* Bitwise exclusive OR
|__ Bitwise inclusive OR
Program 1.5: Program for Bitwise and Bit Shift Operator.
public class Bitwise
{
public static void main(String args[])
t
int c=53
System. out print1n(20<<2);
System.out .print1n(26>>2);
System. out .printIn(acb&acc);
y
output:
86
5{Core Java [BBA(CA): Sem. V1 110 Java Fundamentals
4, Logical operator: The logical 68 operator doesn't check the second condition if the
first condition is false. It checks the second condition only if the first one is true.
logical AND aa
logical OR Il
Program 1.6: Program for Logical Operator.
public class Logical
{
public static void main(String arge[])
t
int a
int 6:
int
System.out .printIn(acb&aa
Greater than
>= Greater than or equal to
< Less than
Less than or equal to
Program 1.8: Program for equality and relational Operator.
public class Euglity
{
public static void main(StringL] args)
{
int x = 105
system.out.printIn(" == y")3
4F(% Ie y)
system.out.printIn("x != y")3
iF(x > y)
system.out.printIn("x > y")3
if < y)
system.out.printIn("x < y")3
SF(x < y)
system.out.printIn("% <= y")3
y
}
xey
7. Assignment Operator: Java assignment operator is one of the most common
operators. It is used to assign the value on its right to the operand on its left.Core Java [BBA(CA): Sem. VI a2 Java Fundamentals
Table 1.2: Assignment Operator, Usage and Effect
Usage
Program 1.9: Program for assignment Operator.
public class Assignment
{
public static void main(string[] args)
{
int a=10;
int b=205
ated; //anatd (291014)
b-n43//o=b-4 (b-20-4)
System.out .printIn(a);
System.out printin(b)5
t
}
Output:
4
16
EX] constant
+ Avalue which is fixed and does not change during the execution of a program is,
called Constants in java, In other words, Java constants are fixed (known as
immutable) data values that cannot be changed. Java supports various types of
constants.Core Java [BBA(CA): Sem. VI 13 Java Fundamentals
Java Consianis
fp
Numeric Constants Non-numeric Constants
Integer Real ‘Character String
Constants Constante Constants Constants
Fig. 11: Classification of Java Constants
L_ Integer Constants:
+ An integer constant is a sequence of digits without a decimal point. For example, 10
and -200 are integer constants. There are three types of integer constants. They are as
follows:
© Decimal integer: For exemple: 24, -55, 0
a Octal integer: Example: 0123,024
9 Hexadecimal integer: Example: 0x23, ox5B
2. Real Constants:
+ Real constants consist of a sequence of digits with fractional parts or decimal points.
These constants are also called floating-point constants. The valid examples of real
constants are 2.3, 0.0034, -0.75, 56.7, etc.
3. Character Constants:
‘+ A single character constant (or simply character constant) is a single character
enclosed within a pair of single quote. The example of single-character constants are:
Sy," ete
4, String Constants:
+ A string constant is a sequence of characters within a pair of double-quotes. The
characters can be alphabets, special characters, digits, and blank spaces. The valid
examples of string constants are: "Hello Java", "192.
Backslash Character Constants:
+ Java provides some special backslash character constants that are used in output
methods. For example, the symbol 'n' which stands for newline character.
+ There are various types of backslash character constants that are supported by java.
The list is given in the belowtable.Core Java [BBA(CA): Sem. VI 14 Java Fundamentals
Table 1.3: Backslash Character Constant
Constants ‘Meaning
‘Nb! back space
Mr form feed
‘\n" new line
carriage return
‘Nt horizontal tab
vu | single quote
| double quote
\ backslash
Types of Comments
‘+ Comments are non-executable statements and are ignored by the Java compiler. The
comments increases the readability of the programs.
‘+ Comments are an integral part of any program. They help the person reading the code
(often you) better understand the intent and functionality of the program.
+ Java language provides three styles of comments as given below:
1 Line Comments:
© It start with two forward slashes (//) and continue to the end of the current line.
Line comments do not require an ending symbol.
© Java's single line comments are proved useful for supplying short explanations
for variables, function declarations, and expressions.
Example: //This is Single Line Comment
2. Block Comments:
Java's multi-line or slash-star or traditional comment is a piece of text enclosed in
slash-star (/*) and star-slash (*/).
Java's multi-line comments are useful when the comment text does not fit into
one line; therefore needs to span across lines.
Example: /*This is Multi Line Comment */
3. Javadoc Comments:
2 Javadoc comments are used to document the new classes you create as a
programmer i. provide information about the class for users of the class toread.
© Java documentation comments is given by /**.n.u."/.
Example: /** Welcome to Wirali Prakashan */Core Java [BBA(CA): Sem. VI 145 Java Fundamentals
Program 1.10; Program for Java comment.
This is a Documentation Connent.
+
public class CommentsDemoExample
{
public static void main(String args{])
{
/* This is a Multi-line Comment */
system.out.printIn("Hello World");// This is a Single Live Comment.
t
yea STRUCTURE OF JAVA PROGRAM
Java Program Structure:
* Java program may contain many classes, of which main( is defined in only one class.
* Classes in Java program contain data members and methods, that operate on the data
members of the class. Methods in Java program may contain datatype declarations
and executable statements.
+ Towrite a Java program, we first define classes and then put them together.
Documentation Section Suggested
Package Statements Optional
Import Statements Optional
Interface Statements Optional
Class Definitions Optional
‘Main method class Essential
Fig. 1.2: Structure of Java Program
‘+ AJava program structure contains following sections
1. Documentation Section: This section is a set of comment lines giving the name of
the program, the author and the other details, which the programmer would like
torefer.
2. Package Statement: In Java files, the first statement allowed is a package
statement, This statement declares a package name and informs the compiler that
the classes defined here belong to this package.
For example: package employee:Core Java [BBA(CA): Sem. VI 116 Java Fundamentals
3.
5.
First Java Program:
1
Navan
Import Statement: Similar to #include statementin C.
For example, import employee.test;
Import statement instructs the interpreter to load the test class contained in
package employee. Using import statement; we can access to classes that part of,
other named packages.
Interface Statement: An interface is like class but includes group of methods
declaration. Interfaces are used when we want to implement multiple inheritance
feature.
Class Definition: Java program may contain many/multiple class definition.
Classes are primary feature of Java program. The classes in Java are used to map
real-world problems.
Main Method Class: Java stand-alone program requires main method as starting
point and this is essential part of program main() method in Java program creates
object of various classes and on reaching, end of the main the program terminate
and the control passes back to the operating system.
public class MyProgran
{
public static void main(String[] args)
{
System.out.print("My First Java Progran");
3
}
Output: My First Java Program
Explanation:
+ Thebasic unit of a Java program is a class. A class called "AyProgran" is defined via the
keyword "class" in Lines 2-7. The braces {
encloses the body of the class.
public class MyProgran
{
}
+ In Java, the name of the source file must be the same as the name of the class with a
mandatory file extension of "java". Hence, this file must be saved as
“MyProgram.javi
-ase-sensitive.
public static void main(String[] args)
{Core Java [BBA(CA): Sem. VI 447 Java Fundamentals
+ Lines 3-6 defines the so-called main() method, which is the entry point for program
execution, Again, the braces {.....} encloses the body of the method, which contains
programming statements.
+ In Line 5, the programming statement system.out.printIn("My First Java
Program") is used to print the string "My First Java Program" to the display console,
A string is surrounded by a pair of double quotes and contain texts. The text will be
printed as it is, without the double quotes. A programming statement ends with a
semi-colon ()
Res EXECUTION PROCESS OF JAVA PROGRAM
+ Bample:
public class MyFirstJavaProgram
{
/* This is my first java program.
* This will print ‘Hello World’ as the output
*/
public static void main(String [Jargs)
{
‘System.out.printIn("Hello World"); // prints Hello World
+
+ Let's look at how to compile, and run the program.
Compiling the Program:
+ To compile the above program, execute the compiler, javac specifying the name of
the source file on the command line. This is shown below:
C:\> javac MyFirstJavaProgram. java
+ Javac compiler creates a file named ‘MyFirstJavaProgram.class' which contains the
byte code version of the program. It is an intermediate representation of the program.
Executing the Program:
+ Toactually run the program you must use the Java application launcher called ‘java’.
This is shown below:
:\> java MyFirstJavaProgram
Output:
C:\> Javac MyFirsthelloProgram. java
C:\> java MyFirsthelloProgram
Hello WorldCore Java [BBA(CA): Sem. VI 118 Java Fundamentals
rl JDK TOOLS
The JDK is a software development environment which is used to develop java
applications and applets.
‘+ JDK (ava Development Kit) provides environment to develop and run java
applications.
* Java Development Kit has a collection of tools for Java Development. JDK contains JRE
along with various development tools like Java libraries, Java source compilers, Java
debuggers, bundling and deployment tools. JRE is part of JDK but can be used
independently to run any byte code (compiled java program). It can be called as JVM
implementation.
‘+ The JDK comes with a set of tools that are used for developing and running Java
program. It includes:
1. Javac: It isa Java compiler.
2. Java: Itis a java interpreter.
3. Javah: tis for java C header files.
4, Jab: Itis Java debugger.
5. AppletViewer: It is used for viewing the applet.
6. Javap: Java disassembler, which convert byte code into program description.
7. Javadoc: It is used for creating HTML document.
ia COMMAND LINE ARGUMENTS
‘Sometimes you will want to pass information into a program when you run it. This is
accomplished by passing command line arguments to main().
+ Acommand line argument is the information that directly follows the program name
onthe command line when it is executed.
+ AJava application can accept any number of arguments from the command line. This,
allows the user to specify configuration information when the application is
launched,
+ Toaccess the command line arguments inside a Java program is quite easy - they are
stored as strings in a string array passed to the args parameter of main(). The first
command line argument is stored at args[0], the second at args[1], and soon.
+ The following program displays all of the command line arguments that it is called
with:
public class ConandLine
{
public static void main(String args[])
t
for(int 1 = @} icargs.length; i++)
{
system.out.printin(“args[" + i + "J: "+ args[i]);
}
}Core Java [BBA(CA): Sem. VI 119 Java Fundamentals
‘Try executing this program as shown here:
Sava ConmandLine this is a command line 20@ -100
This will produce the following output:
args[@]: this
args[1]: is
args[2]: a
args(3]: command
args[4]: Line
args[5]: 268
args[6]: -100
Example: The following Program illustrate that how to take input as two numbers from
‘the user and display the addition with two input methods: BufferedReader and Command
Line arguments.
import java.io.*;
import java.util.Scanner;
class demo
public static void main(String arg[]) throws Exception
{
system.out .print1n(”
methods") 5
//input using BufferedReader
dition of two numbers using three input
int x,y5
BufferedReader b=new BufferedReader(new InputStreanReader
(system.in))5
system.out.printin(“enter two numbers");
xeInteger.parseInt(b.readLine());
yeInteger.parsernt(b.readLine());
System.out println("sum is=" +(x4y))5
// Input using Connand line arguments
int
nteger.parseInt(arg[@]);
l-Integer.parseInt(arg[1])5
int sum
sumi=a+ds
System.out.printIn(sumt) ;Core Java [BBA(CA): Sem. VI 120 Java Fundamentals
+ When we accepting input from console we need to BufferedReader and scanner class.
+ BufferedReader improves performance by buffering input. The BufferedReader class
does have a method called readline that does return aline of text as type by the user.
‘+ InJava, the java.util Scanner or Scanner class is one of them which allows the user to
read values of various typesin java.
+ Anarray is a group of similar type 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,
+ Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same
type.
‘+ Array is a contiguous fixed-length structure for storing multiple values of the same
type. Array in Java is index based, first element of the array is stored at 0 index.
Fist ndex dene,
o] 1 2 3 4 5 6 7 \8 Se —indoes
| ray tenth is 10
ig. 13: Arrays
Single-Dimensional (1D) Array
+ Anarray is a sequence of variables of the same data type. Array having only one
subscript variable is called One-Dimensional array.
+ Itis also called as Single-Dimensional Array or Linear Array.
+ Aone-dimensional array is, essentially, a list of similar type variables, To create an
array, you first must create an array variable of the desired type.
* Todeclare an array, you specify the name of the array and the data type, as you would
for any other variable, Adding an empty set of brackets ([ ]) indicates that the variable
is an array,
+ The general form/syntax ofa one-dimensional array declaration is given below:
datatype array_name [];Core Java [BBA(CA): Sem. VI 21 Java Fundamentals
+ 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
ofint":
int month_days{13
Instantiating Arrays:
+ Aswe mentioned earlier, Java arrays are objects, so to allocate memory for an array,
you need to instantiate the array using the new keyword. Here, is the syntax for
instantiating an array:
array_name = new datatype[size];
Where, size is an expression that evaluates to an integer and specifies the number of
elements in the array.
For example: month_days = new int(12];
Assigning Initial Values to Arrays:
+ Java allows you to instantiate an array by assigning initial values when the array is
declared. To do this, you specify the initial values using a comma-separated list
within curly braces as given below:
datatype array_nane[] = {value@, valuel, value2, ... valueN};
‘Where, valueN is an expression that evaluates to the data type of the array and is the
value to assign to the element at index N.
+ Note that, we do not use the new keyword and we do not specify a size for the array,
the number of elements in the array is determined by the number of values in the
initialization list.
+ Forexample, following statement declares and instantiates an array of Numbers:
int nine = 95
int[ ] Numbers = {2, 4, 3, 8, one, one + 2, 13, 14, 17, 18}
* Because 10 values are given in the initialization list, this array has 10 elements,
Notice that the values can bean expression, for example, one and one + 2.
Program 1.11: Program for one-dimensional (1D) array.
import java.util.
class arraydeno
t
public static void main(String args{])
{
int a[]={2,4,6,3,1}5
system.out..printIn(”
System.out.printIn("Elements in array a:" + a.length);
lunber of elements in array a: "+a.length);Core Java [BBA(CA): Sem. VI 422 Java Fundamentals
for(int 8034
system.out.printIn();
3
3
}
Output:
e0000
e000
e0000
e0000
Program 1.16: Program addition of two matrices
class Testarray
{
public static void main(String args[])
{
//creating two matrices
int af][]=((1,3,4),(3,4,5)}5
int b[][]=((1,3,4},(3,4,5}}5
Jicreating another matrix to store the sun of two matrices
Ant ¢[][]=new int [2][3];
//adding and printing addition of Two matrices
for(int 1=01<2;i++)
{
For (int 3-055<3;5++)
t
[4] (5]=a[i](5]+e(3] 0515
‘System.out .print(c[i][]+"
+
system.out .printin()3//new LineCore Java [BBA(CA): Sem. VI 427 Java Fundamentals
Program 1.17: Program for sorting elements in array.
import java.util.Arrays;
class SortIntArrayExample
t
public static void main(String[] args)
{
J/create an int array
Ant[] i1 = new ant(}{3,2,5,4,1}5
Jiprint original int array
System.out.print("Original Array: ");
for(int index=0; index < ii.length ; index++)
+ 4i[index]);
system.out.print("
Arrays.sort(i1)5
H[print sorted int array
System.out.print("Sorted int array: ")3
for(int index-@; index < id-length ; indexs+)
System.out print(" "+ i1[index]);
int[] 42 = new ant{]{5,2,3,1,4}5
Arrays.sort(i2,1,4)5
JIprint sorted int array
Systen.out.print ("Partially Sorted int array
for(int index=9; index < i2.length ; index++)
+ i2[index]) ;
system.out.print(*
+
Output:
Original Array: 3.2541
Sorted int array: 12345
Partially Sorted int array: 51234
Program 1.18: Program to reverse elements in array.
import java-util.*;
class Reversearray
{
public static void main(String args[])
{
// Create Java.util.Scanner object for taking input
Scanner senew Scanner (System. in);ore Java (BBA(CA): Sem. VI 128 Java Fundamentals
// Take no.of elements and store it inn
system.out.println("Enter the no.of elenents
int _n=s.nextInt()3
1] Create array of size n
int af]=new int{n];
// Read clenents into the array
Systen.out.printIn("Enter the elements into the array:");
for(int 4=05i elements)
10. | boolean equals(object another) This method checks the equality of
string with object.
11, | boolean isénpty() This method checks if string is empty.
a2. | string concat(string str) ‘This method concatenates specified
String replace(char old, char new)
string.
This method replaces all occurrences
of specified char value.
14.
String replace(CharSequence old,
CharSequence new)
String trim()
This method replaces all occurrences
of specified CharSequence.
This method returns trimmed string
omitted leading and trailing spaces.
16. | String split(string regex) This method returns splitted string
matching regex.
47, | String split(String regex, int | This method returns splitted string
Limit) matching regex and limit.
18._| string intern() ‘This method returns interned string.
19. | int indexof(int ch) This method returns specified char
value index.
20. | int indexoF(int ch, int fromIndex) | This method returns specified char
value index starting with given index.
21 | int indexo#(string substring) This method returns specified
substring index.
contd...ore Java [BBALCAY: Sem. VI 132 ova Fundamentals
22. | int indexof(String substring, int [This method returns specified
fromIndex) substring index starting with given
index.
23 | String toLowerCase() This method returns string in
lowercase.
24. | String toLowerCase(Locale 1) This method returns string in
lowercase using specified locale.
25. | String toUpperCase() This method returns string in
uppercase.
26. | String toUppercase(Locale 1) This method returns string in
uppercase using specified locale.
String Class Constructors:
* Constructors are used to initialize the object. The string class supports several
constructors.
‘+ The following table shows the constructors of the string class.
Table 1.5: String Class Constructor
ne. Constructor Description
string()
This constructor creates an empty
string.
String(String value)
This constructor creates a new string
that is a copy of the given string.
string(char[] value)
This constructor constructs a new
string based on the character array.
4, | String(char[] value, int begin, | This constructs a new string based on
int count) the character array starting from the
position begin which is ‘count’
characters long.
5. | String(bytel] value) This constructor creates a new string
by converting the given array of bytes.
6. | String(byte[] value, int offset, | This constructor creates a new string
int length) by converting the given sub of array of
bytes.
7. | String(Stringsuffer buffer) This constructor creates a new string
String(char[] value, int begin,
int count, String enc) throws
Unsupportedencoding Exception
String(char[] value, string enc)
‘throws Unsupportedéncoding
Exception
based ona StringBuffer value.
This constructor creates a new string
based on the given byte array and uses
given character encoding that is
denoted by enc.
This constructor creates a new string
based on the given byte array and uses
given character encoding that is
denoted by enc.Core Java [BBA(CA): Sem. VI 133 Java Fundamentals
StringBuffer
‘+ It is a peer class which provides the functionality of strings. The string generally
represents fixed length, immutable character sequence whereas StringBuffer
represents growable and writeable character sequences.
+ StringBuffer may have some characters and if needed substring can be inserted in
the middle or appended at the end. StringBuffer automatically provides a room to
grow such additions,
+ Java generally manipulate the strings using + as overloaded operator. StringBuffer
class in Java is used to created mutable (modifiable) string, The StringBuffer class in
Java is same as String class except it is mutable i.e, it can be changed.
+ StringBuffer class is a mutable class unlike the String class which is immutable. Both
the capacity and character string of a StringBuffer Class. StringBuffer can be
changed dynamically.
Advantages of StringBuffer Class:
1. Alternative to String class.
2. Can be used wherever a string is used.
3. More flexible than String,
‘+ The StringBuffer defines three types of constructors which we use to initialize the
string value.
1. StringBuffer)
2, StringBuffer (int size)
3. StringBuffer (String str)
‘+ The first type is the default constructor as it has no parameters. It reserves room for
16 characters without reallocation. The second, type accepts an integer argument
which explicitly sets the size of buffer. In third case, the string argument sets the
initial contents of the StringBuffer object and reverse room for 16 more characters.
These 16 characters room is allocated when no specific buffer length is requested.
This is because reallocation is a costly process in terms of time.
‘+ The current length of a StringBuffer can be found via length() method and the total
allocated capacity can be found through capacity() method.
+ The general forms are:
int Length();
and
int capacity();
+ StringBuffer creates string objects that can be changed. String object is
manufactured which contains the substring. In this the original string is unaltered
and immutability remains intact.
‘+ String provides a substring() method which returns a new string. It contains a
specified portion of the invoking string. This method is substringQ.Core Java [BBA(CA): Sem. VI 134 Java Fundamentals
The syntax is given below:
String subString(int startIndex, int endIndex)
The startindex specifies the beginning index and endindex tells us about stopping
point.
StringBuffer Class Methods: Here, is the list of important methods supported by
StringBuffer class:
1. public StringBuffer append(string s): Updates the value of the object that
invoked the method.
2, public stringbutfer reverse(): Reverses the value of the StringBuffer object
that invoked the method.
3. public delete(int start, int end): Deletes the string starting from start
index until end index.
4. public insert(int offset, int i): Inserts an string s at the position
mentioned by offset.
5. replace(int start, int end, String str): Replaces the characters in a
substring of this StringBuffer with characters in the specified String.
Here, is the list of other methods (Except set methods ) which are very similar to
String class:
1. int capacity(): Returns the current capacity of the String buffer.
2. char charAt(int index): The specified character of the sequence currently
represented by the string buffer, as indicated by the index argument, is returned.
3. void ensureCapacity(int minimunCapacity): Ensures that the capacity of the
buffer is at least equal to the specified minimum.
4, void getchars(int sreBegin, int srctnd, char[] dst, int dstBegin):
Characters are copied from this string buffer into the destination character array
ast.
5. int indexoF(string str): Returns the index within this string of the first
‘occurrence of the specified substring.
6. int indexof(string str, int fromindex): Returns the index within this string
of the first occurrence of the specified substring, starting at the specified index.
7. int lastIndexof(string str): Returns the index within this string of the
rightmost occurrence of the specified substring.
8 int lastIndexof(string str, int fromIndex): Returns the index within this,
string of the last occurrence of the specified substring.
9, int Length(): Returns the length (character count) of this string buffer.
10. void setCharat(int index, char ch): The character at the specified index of
this string buffer is set to ch.
11, void setLength(int nevLength): Sets the length of this String buffer.Core Java [BBA(CA): Sem. VI 135 Java Fundamentals
12, Charsequence subSequence(int start, int end:
sequence that is a subsequence of this sequence.
Returns a new character
33, string substring(int start): Returns a new String that contains a
subsequence of characters currently contained in this StringBuffer.The substring
begins at the specified index and extends to the end of the StringBuffer.
14, String substring(int start, int end): Retums a new String that contains a
subsequence of characters currently contained in this StringBuffer.
15, String toString(): Converts to a string representing the data in this string
buffer.
Program 1.20: Program to showuse of substring.
/Juse of substring
class strtry
{
public static void main(String args[])
£
String stl = "Java is platform independent";
// to construct a substring we write
String sub = st1.substring(9, 16);
// lets print these values
‘System.out.printIn("Original string is: + sti");
System.out.printIn("Substring is: + sub");
} end main
} J/end class
Output:
Original string is: Java is platform independent
Substring is: platform
Difference between String and StringBuffer: T
+ String objects are constants and immutable whereas StringBuffer objects are not.
18]
+ StringBuffer Class supports growable and modifiable string whereas String class
supports constant strings.
‘+ Strings once created we cannot modify them. Any such attempt will lead to the
creation of new strings, Whereas StingBuffer objects after creation also can beable to
delete or append any characteres to it.
‘+ String values are resolved at run time whereas StringBuffer values are resolved at
compile time.Core Java [BBA(CA): Sem. VI 136 Java Fundamentals
[BEB suicr in PACKAGES AND CLASSES
Defining a Package:
+ Apackage is a collection of classes and interfaces.
+ Apackage does not contain the source code of any type of Java file. Each Java source
code file isa collection of one or more classes, or one or more interface with their
members.
BEE] java.util:- scanner, Date, Math
+ Javanutil Package contains the collections framework, legacy collection classes, event
‘model, date and time facilites, internationalization, and miscellaneous utility classes
(astring tokenizer, a random-number generator, anda bit array).
+ Following are the Important Classes in Java.util package:
1. Scanner:
+ Scanner is a class in java.util package used for obtaining the input of the primitive
types like int, double, etc. and strings. It is the easiest way to read input in a Java
program though not very efficient if you want an input method for scenarios where
time is a constraint like in competitive programming,
+ Methods of scanner class:
1. nextBoolean() : Reads boolean value from the user.
2. nexteyte() : Readsa byte value from the user.
3. nextDouble() : Readsa double value from the user.
4. nextFloat() : Readsa float value from the user.
5. nextint() Reads a int value from the user.
6. nextLine() : Readsa String value from the user.
7. nextiong() + Reads along value from the user.
8 nextShort() : Readsa short value from the user.
‘+ Touse the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use the
NextInt () method, which is used to read integer value from user:
Program 1.21: The following Program illustrate that how to take input as two numbers
from the user and display the addition with three input methods: Scanner.
import java.io.*5
import java.util Scanners
public class demo
{
public static void main(String arg[]) throws Exception
t
Scanner s=new Scanner(System. in) ;Core Java [
1A(CA): Sem. VI 137 Java Fundamentals
System.out.println(“enter two numbers");
int Lss.nextInt();
int nes.nextInt();
int sui
sum=L+n5
System.out.printIn("sum i
}
+
Output:
enter two numbers
5
5
sun is-1@
2. Dati
‘+ Java does not have a built-in Date class, but we can import the java.time package to
work with the date and time API. The package includes many date and time classes. For
example:
+ Dateand Time classes:
1. Localbate + Represents a date (year, month, day (yyyy-MM-dd))
2, LocalTime Represents a time (hour, minute, second and nanoseconds
(HH-mm-ss-ns))
3. LocalDateTime ‘Represents both a date and a time (yyyy-MM-dd-HH-mm-
ss-ns)
4, DateTimeFormatter_: Formatter for displaying and parsing date-time objects
Program 1.22: To display current date and time with formatting.
Anport java.time. LocalbateTine;
import java.time. format. DateTimeFormatter
public class Main
{
public static void main(String[] args)
{
LocalDateTime myDatedbj = LocalDateTime.now();
system.out.println("Before formatting: " + myDatedbj);
DateTineFormatter myFormat0bj = DateTineFormatter.ofPattern("dd-™M-
yyyy HH:mm: ss") 5
String formatteddate = myDate0bj.format (nyFormatObj) ;
system.out.println("After formatting: " + formattedDate);
+Core Java [BBA(CA): Sem. VI 138 Java Fundamentals
output:
Before formatting: 2021-8-03707:40:54.347413
After formatting: @3-08-2021 07:40:54
+ The "T" in the example above is used to separate the date from the time. You can use
the DateTimeFormatter class with the of Pattern() method in the same package to
format or parse date-time objects.
3. Math:
* java Math class provides several methods to work on math calculations like min(),
max(), avg0, sind, cos), tang, roundd, ceil0, floor), abs() ete.
+ Unlike some of the StrictMath class numeric methods, all implementations of the
equivalent function of Math class can't define to return the bit-for-bit same results.
This relaxation permits implementation with better-performance where strict
reproducibility is not required.
‘+ If the size is int or long and the results overflow the range of value, the methods
addExact(, subtractExact), multiplyExact(, and tolntExact) throw an
ArithmeticException.
+ For other arithmetic operations like increment, decrement, divide, absolute value,
and negation overflow occur only with a specific minimum or maximum value. It
should be checked against the maximum and minimum value as appropriate.
Math Methods:
+ The javadang.Math class contains various methods for performing basic numeric
operations such as the logarithm, cube root, and trigonometric functions etc. The
various java math methods are as follows:
Table 1.6: Basic Math methods
Method Description
Math.abs() It will return the Absolute value of the given value,
Math max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Nath.round() It is used to round of the decimal numbers to the nearest
value,
Nath.sqrt() Itisused to return the square root of a number.
Math.cbrt() Itis used to return the cube root of a number.
Nath.pow() It returns the value of first argument raised to the power to
| second argument.
Nath.signum() It is used to find the sign of a given value,
Nath.ceil() It is used to find the smallest integer value that is greater
than or equal to the argument or mathematical integer.
contd...Core Java [BBA(CA): Sem. VI
139 Java Fundamentals
Math.copySign()
Nath.nextafter()
It is used to find the Absolute value of first argument along
with sign specified in second argument.
It is used to return the floating-point number adjacent to the
firstargument in the direction of the second argument.
Math.nextUp()
It returns the floating-point value adjacent to d in the
direction of positive infinity.
Math.nextDown()
It returns the floating-point value adjacent to d in the
direction of negative infinity.
Nath.floor()
It is used to find the largest integer value which is less than
or equal to the argument and is equal to the mathematical
integer of a double value.
Math.FloorDiv()
It is used to find the largest integer value that is less than or
equal to the algebraic quotient.
Math.random()
It returns a double value with a positive sign, greater than or
equal to 0.0 and less than 1.0.
Math.rint()
It returns the double value that is closest to the given
argument and equal to mathematical integer.
Math.hypot()
It returns sqrt? +’) without intermediate overflow or
underflow.
Math.ulp()
It returns the size of an ulp of the argument.
Math.getExponent()
It is used to return the unbiased exponent used in the
representation of a value,
Math. TEEeremainder()
It is used to calculate the remainder operation on two
arguments as prescribed by the IEEE 754 standard and
retums value,
Math.addexact()
It is used to return the sum of its arguments, throwing an
exception if the result overflows an int or long.
Math.subtractExact ()
| Math multiplyéxact()
It returns the difference of the arguments, throwing an
exception if the result overflows an int.
It is used to return the product of the arguments, throwing
an exception if the result overflows an int or long.
Math.incrementéxact ()
It returns the argument incremented by one, throwing an
exception if the result overflows an int.
Math.decrenentExact ()
It is used to return the argument decremented by one,
throwing an exception if the result overflows an int or long.
Math.negateéxact()
It is used to return the negation of the argument, throwing
an exception if the result overflows an int or long.
Math.tointexact()
It returns the value of the long argument, throwing an
exception if the value overflows an int.Core Java [
1A(CA): Sem. VI 1.40 Java Fundamentals
Program 1.23: Pragram for math class.
public class JavaMathExanple1
{
public static void main(String[] args)
{
double x
285
43
Systom. out .print1n( "Maximum number of x andy is:
System.out.printn("Square root of y is: " + Math.sqrt(y));
System.out.printin("Power of x and y is: " + Math.pom(x, y))3
System.out.printIn("Logarithm of x is: “+ Math.log(x));
System out.println("Logarithn of y is: " + Math.log(y));
+ Mati. Logi@(x)) 5
+ Math, Logi@(y));
+Hath. loetp(x)):
hath exp(x)) 5
" aMath. expm(x))3
double y
smathemax(x, y))5
System.out.println("Logi® of x is:
System.out.println("logi@ of y is:
System.out.printIn("logip of x is:
System.out.printIn("exp of a i
systen.out.printin("expm of a 4:
+
Output:
Maximum number of x and y 4:
Square root of y is: 2.
Pouer of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
logi@ of x is: 1.4471580313422192
Logi® of y is: 0.6020599913279624
logip of x is: 3.367295879986474
exp of a is: 1.446257064201475612
expmi of a is: 1.446257064290475E12
FEE) java.tang
+ Provides classes that are fundamental to the design of the Java programming language.
The most important classes are object, which is the root of the class hierarchy, and
class, instances of which represent classes at run time.Core Java [BBA(CA): Sem. VI a Java Fundamentals
+ Following are the Important Classes in Java-lang package:
1. Boolean: The Boolean class wraps a value of the primitive type boolean in an
object.
2. Byte: The Byte class wraps a value of primitive type byte in an object.
3. Character - Set 1, Set 2: The Character class wraps a value of the primitive
type char in an object.
4, Character.Subset: Instances of this class represent particular subsets of the
Unicode character set.
5. Character.UnicodeBlock: A family of character subsets representing the
character blocks in the Unicode specification.
6. Class - Set 1, Set 2: Instances of the class Class represent classes and
interfaces in a running Java application.
7. ClassLoader: A class loader is an object that is responsible for loading classes.
ClassValue: Lazily associate a computed value with (potentially) every type.
9. Compiler: The Compiler class is provided to support Java-to-native-code compilers
and related services.
2
10. Double: The Double class wraps a value of the primitive type double in an object.
11, Enum: This is the common base class of all Java language enumeration types.
12, Float: The Float class wraps a value of primitive type float in an object.
13, InheritablethreadLocal: This class extends Thread Local to provide inheritance
of values from parent thread to child thread: when a child thread is created, the
child receives initial values for all inheritable thread-local variables for which the
parent has values.
14, Integer: The Integer class wraps a value of the primitive type int in an object.
Long: The Long class wraps a value of the primitive type long in an object.
16.hath - Set 1, Set 2: The class Math contains methods for performing basic
numeric operations such as the elementary exponential, logarithm, square root,
and trigonometric functions.
17. Number: The abstract class Number is the superclass of classes BigDecimal,
BigInteger, Byte, Double, Float, Integer, Long, and Short,
18, object: Class Object is the root of the class hierarchy.
19, Package: Package objects contain version information about the implementation
and specification of a Java package.
20. Process: The ProcessBuilder.start() and Runtime.exec methods create a native
process and return an instance of a subclass of Process that can be used to control
the process and obtain information about it.
21, ProcessBuilder: This class is used to create operating system processes.
22, ProcessBuilder.Redirect: Represents a source of subprocess input or a
destination of subprocess output.
&Core Java [BBA(CA): Sem. VI a2 Java Fundamentals
23, Runtime: Every Java application has a single instance of class Runtime that allows
the application to interface with the environment in which the application is
running.
24, RuntimePermission: This class is for runtime permissions.
25, SecurityManager: The security manager is a class that allows applications to
implement a security policy.
26. Short: The Short class wraps a value of primitive type short in an object.
27, StackTraceElenent: An element in a stack trace, as returned by
‘Throwable.getStackTrace).
28, strictNath - Seti, Set2: The class StrictMath contains methods for performing
basic numeric operations such as the elementary exponential, logarithm, square
root, and trigonometric functions.
29, String - Seti, Set2: The String class represents character strings.
30, StringBuffer: A thread-safe, mutable sequence of characters.
31, StringBuilder: A mutable sequence of characters.
32, System: The System class contains several useful class fields and methods.
33, Thread: A thread is a thread of execution in a program.
34, ThreadGroup: A thread group represents a set of threads.
35, ThreadLocal: This class provides thread-local variables.
36, Throwable: The Throwable class is the superclass of all errors and exceptions in
the Java language.
37. Void: The Void class is an uninstantiable placeholder class to hold a reference to
the Class object representing the Java keyword void.
Program 1.24: Write a Java program to accept ‘n’ numbers through command line and
store all prime numbers into an array and display elements of array.
Amport java.io.*5
public class ArrayDeno2
{
public static void main (String args[]) throws IOException
t
Ant j,s,4,k=8,m=0,n5
int r[J=new int{10] ;
int prine[]=new int[10] ;
int perfect[]=new int[19] 3
BufferedReader br=new Buf feredReader(new _TnputStreanReader
(systen.in))
System.out.printIn(“Enter the Number of Elements :=>");
n=Integer.parseInt(br.readLine());Core Java [BBA(CA): Sem. VI 143 Java Fundamentals
for (is0;icnjier)
{
System.out.printIn("Enter the "sit" Number of the Array
p[i]= Integer. parsernt(br.readLine());
}
For(j=053<10;3++)
{
int fla
FCPS
t
continue;
+
else
t
+
if (Flag
{
primefk]=r[3]5
key
y
}
System.out.printIn("\nPrime Nunbers are");
For(1-jickji++)
{
system.out. print (prime[i]+"
}
>
}
Output:
Enter the Number of Elenents :=>
a
Enter the @ Number of the Array :
3Core Java [BBA(CA): Sem. VI
Enter the 1 Number of the Array :
2
Enter the 2 Number of the Array
4
Java Fundamentals
Prime Numbers are
3
2
Program 1.25: Java program to count vowels, consonants, digits, and spaces of given
word.
a5)
public class Main
{
public static void main(String[] args)
1
string line = "This website is aw3son3."5
int vonels = @, conscnants = @, digit:
line = Line.toLowercese();
for (int i = 0; 4 < line.length(); 14)
{
char ch = line.charAt(i);
// check if character is any of a, e, i, 0, u
if (ch == 'a" [| ch TL ch Ich
{
s4vowels;
3
// check if character is in between a to z
else if ((ch >= ‘a’ && ch <= 'z"))
{
+4consonants;
}
// check if character is in between @ to 9
else if (ch >= '@' && ch <= '9")
{
@, spaces
sHdigits;
+
// check if character is a white space
else if (ch ==" ')
{
+4spaces;Core Java [BBA(CA): Sem. VI 145 Java Fundamentals
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: "
+ consonants) ;
system.out.printIn("Digits: " + digits);
System.out.printin("khite spaces: " + spaces);
}
Output:
Vowels: 7
Consonants: 11
Digits: 2
nite spaces: 3
Program 1.26: Write a java program to accept n names of cities from users and display
them in descending order. EH
import java-util.*;
class City
t
//eeclaration of array
string af];
int 3
city()
{
Scanner senew Scanner(Systen.in);
system.out.print("Enter how many city you want to enter +
enextInt()5
Iiredeclartion of array
asnew String[n];
1/70 accept values
for(int 1=0;18)
{
temp=a[i]5
alil-a[J]s
alJ]=temp;
+
+
+
system.out.printIn("Sorted Cities are ");
for(int i-@sicnsitt)
{
system.out.print(a[il+" ")3
//7o create object
public class Testcity
{
public static void main(String args{])
{
Output:
Enter
Enter
Enter
Enter
Enter
Enter
City ob;
how many city
{ist} element:
{ist} element:
{as1} element:
{4+1} element:
{4s1} element:
Sorted Cities are
en City ()5
obj .display();
you want to enter : 5
Pune
satera
Kolhapur
Nagpur
Pampr
Kolhapur Nagpur Pimpri Pune SataraCore Java [BBA(CA): Sem. VI 147 Java Fundamentals
Erte
>
>
James Gosling is called Father of Java Programming. Java is an Object Oriented
Programming language means Java enables us not only to organize our program
code into logical unit called objects but also to take advantage of encapsulation,
inheritance and polymorphism and so on.
Various features of java includes Simple, Secure, Portable, Object-oriented,
Robust, Multithreaded, Architecture-neutral, Interpreted, High Performance,
Distributed, Dynamic.
Java defines eight primitive types of data: byte, short, int, long, char, float, double,
and Boolean.
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.
Array is a data structure where we store similar elements. We can store only fixed
set of elements in a Java array. Types of array-1D array, 2D array.
A one-dimensional array having only one subscript. In Java 2D array is a matrix of
rows and columns.
Java Math class provides several methods to worlon math calculations like minQ,
max(), avg0, sin0, cos0, tan(), round), ceil, floor(, abs( ete.
Scanner is a class in java.util package used for obtaining the input of the
primitive types like int, double, etc. and strings.
A package is a collection of classes and interfaces.
Peeters Oey
1
Which of these is necessary to specify at time of array initialization?
(a) Row (®) Column
(©) Both Row and Column (A) None of the mentioned
Which of these classes is not included in java.lang?
(@) Byte (&) Integer
(©) array (@ Class
Which of these is a super class of wrappers Double 6 Integer?
(@) Long () Digits
(©) Float (@) Number
Which of the following package stores all the simple data types in java?
(@) lang () java
(©) util (@) java.packages
Which one of the following will declare an array and initialize it with five
numbers?
(@) Array a=new Array(5); () int (Ja = (23,22,21,20,19};
(©) inta {] = new int{s}; (@) int (5) array;Core Java [BBA(CA): Sem. VI 1.48 Java Fundamentals
6 Which Scanner class method is used to read integer value from the user?
(a) next) (0) nextinteger)
(©) nextint) (@) readint()
7. Whatis the output of this program?
class increment
{
public static void main(String args[])
t
int g = 33
System.out.print(++g * 8);
}
+
(@) 25 (&) 24
(©) 32 (@ 33
8, Which is the correct syntax to declare Scanner class object?
(@) Scanner objectName= Scanner();
(&) Scanner objectName= new Scanner();
(©) Scanner objectName= Scanner(system.in);
(@) Scanner objectName= new Scanner(System.in);
9. How to format date from one form to another?
(2) SimpleDateFormat (&) DateFormat
(©) SimpleFormat (@) DateConverter
10, Howr to format date from one form to another?
(2) SimpleDateFormat (&) DateFormat
(©) SimpleFormat (@) DateConverter
Answers
1@ | 2© | 3@ | 4@ | 5 | 6@ | 7 | 8@ | 9) | 10a)
Paredes
Q1 Answer the following questions in short.
1. Whatis Java?
Why Java is platform-neutral language?
Explain the secure feature of Java.
Why Java is called portable?
‘How to compile Java program?
How to run Java program?
ov aeyeCore Java [BBA(CA): Sem. VI 149 Java Fundamentals
Ql Answer the following Questions.
PReraueene
Explain atleast five features of Java.
Why Java needs compiler and interpreter?
What is a variable? What rules can be applied to have a valid variable name?
Explain primitive data types in detail.
Explain reference or non-primitive data types.
Whats array?
‘How a comment is added in java program?
What are the types of array?
Explain java.lang package.
10, Explain java.util package.
11, Explain scanner, math, date class in java.
12, Predict the output:
Class Test
Public static void main (string [ ] args)
‘
int [] x= (4, 2,3, 4}5
int ly =x5
x = new int [2];
for (int i = @; i < y.length; i ++)
System. out. println (y [i])3
a
2
3
4
QiIl Define the terms.
1
ayaen
Array
string
Package
Variable
Constant
‘Type castingCore Java [BBA(CA): Sem. VI 150 Java Fundamentals
Pouce
[Winter 2038|
1. Describe any two features of Java programming language. a
Ans. Referto Section 1.1.2.
2. What are differences between String and StringBuffer class?
Ans. Refer to Section 17.22.
3. "Import statement is not essential in java." True/False. Justify.
Ans. Refer to Section 1.3.
4. Explain Array in Java. How does it differ from C++?
Ans. Refer to Section 17.1.
5. Write a Java program to accept 'n' numbers through command line and store all
prime numbers into an array and display elements of array.
Ans. Refer to Program 1.24.
6. Write a Java Program that displays the number of non-vowels in the given
word.
Ans. Refer to Program 1.25.
‘Summer 2019]
1. Does the order of public static void matter in main method.
Ans. Refer to Section 13.
2. Write a java program to accept n names of cities from users and display them in
descending order.
Ans. Refer to Program 1.26.2
Classes, Objects and Methods
Learning Objectives..
To understand Basic Concepts of Objects and Classes.
{Ml To study Constructors and Methods.
H To learn Nested Classes, Inner Class, Anonymous Inner Class in Java.
'| To learn New Operator, this and static keyword, finalize() method.
Fa cuss anp onject
+ In Object Oriented Programming (OOP) technique, we design a program using objects
and classes. Object is the physical as well as logical entity whereas class is the logical
entity only.
+ Java is not fully object oriented programming language because it makes use of eight
data types such as boolean, int, char, double, long, short, float and byte which are not
object.
EBB] overview of classes
+ Classes in Java provide a convenient method for packing together a group of logically
related data items and functions that work on them.
+ In Java language, the data items are called fields and the functions are called
methods. Calling a specific method in an object is described as sending the object of
message,
+ A dass can be defined as, "a template/blueprint that describes the behaviors that
object of its type support’
‘+ Acass is declared by use of the class keyword. The classes that have been used up to
this point are actually very limited examples of its complete form.
eaCore Java [BBA(CA): Sem. VI 22 Classes, Objects and Methods
+ Asimplified general form/syntax of a class definition is shown here:
class classname
{
type instance-variable1;
type instance-variable2;
‘type instance-variableN;
‘type methodnamel (paraneter-list)
{
/1 body of method
}
‘type methodname2(parameter-List)
{
+
‘type methodnameN(parameter-List)
{
+
}
+ Example of Class:
Class Employee
{
11 body of method
11 body of method
int Emp1D;
float salary;
Program 2.1: Program for class.
public class JavaClassexemple
t
public static void main(String[] arg)
t
for (int i= 05 ics itt)
‘
system.out.printin("Number is: “+1);
}
}
}
Output:
Nunber is: @
Number is: 1
Nunber is: 2
Nunber is: 3Core Java [BBA(CA): Sem. VI 23 Classes, Objects and Methods
ERE) overview of objects
‘Ateal-world entity that has state and behavior is known as an Object.
These real-world objects share two characteristics i. state and behavior.
Example: A cat has states - color, name, etc. as well as behaviors like walking and
eating.
In simple words, object is an instance of a class,
Fig. 2.1 shows a real world example of class and objects. Fig, 2.1 shows class Car has
objects like Audi, Nissan, Volvo.
class objects
Audi Nissan Volvo
Example of Class and Object
Declaring Objects:
‘When you create a class, you are creating a new data type. You can use this type to
declare objects of that type. However, obtaining objects of a class is a two-step
process.
() Declaration:
(i) instantiation (Creating Objects)
© We have to specify what type (ie. class) the object will be. A variable declaration
with a variable name with an object type.
9 Syntax: objectnane;
Where, classname is the name of the already defined class and the objectname is a
valid identifier.
2 Objects are created using the ‘new’ keyword. This ‘new’ keyword creates an object
of the specified class and returns the reference of that object.
> The ‘new’ keyword is followed by a call to a constructor. This call initializes the
new object.
9 Syntax: = new classname([arguments]) 5
> Letus create an object for the Box class.
Box mybox = new Box();
> This statement combines the two steps just described. It can be rewritten like this
to show each step more clearly:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box objectCore Java [BBA(CA): Sem. VI 24 Classes, Objects and Methods
Statement Effect
Box mybox; null
mybox.
‘mybox = new Box(); —}—|_ win
mybox Height
Depth
Box object
Fig. 2.2: Object Instantitation
(iii) Accessing Class Members:
«The dot operator () or member selection operator is used to access the instance
variables of the class.
‘© We cannot access the instance variables outside of the class without referring to
the object.
© Member access follows the following syntax:
objectname.variablename
Here, the objectname is the name of the object and variablename is name of the
instance variable.
So, the instance variables of the class Employee can be accessed as,
Employee.£_id=1234;
Employee. salary=300005
Program 2.2: Program for declaration and instantiation of object.
class Myobject
{
public void getMessage()
t
System.out.print1n("Object Created and Functioned Called");
+
public static void main(string args{])
{
MyObject x = new MyObject(); //x is declared and initialized with an
instance of MyObject
x.getHessage();
+
Output:
Object Created and Functioned CalledCore Java [BBA(CA): Sem. VI 25 Classes, Objects and Methods
Difference between Class and Object:
‘+ There are many differences between object and class. A list of differences between,
object and class are given below:
Table 2.1: Difference between Class and Object
| sr.No. Class Object
1. _| Class is a blueprint or template from | Objectis an instance of a class.
which objects are created.
2. | Classisa group of similar objects. | Object is a real world entity such as
pen, laptop, mobile, bed, keyboard,
mouse, chair etc.
3.__| Class is a logical entity. Objects a physical entity.
4,__| Class is declared using class Keyword | Object is created through new
like class Student{ ... } keyword like, Student si=new
Student ();
5. _ | Classis declared once. Object is created many times as per
requirement
6. _ | Class doesn't allocated memory when | Object allocates memory when it is
itis created. created.
122) OBJECT REFERENCE
The objects are constructed and allocated in memory independently from the
declarations of variables. Specifically:
1. Objects denoted by a literal (such as literals of type String, e.g., "foo",
are allocated in memory at compilation time.
2. Allother objects must be constructed and allocated through an explicit statement.
‘+ Avariable whose type is a class contains a reference to an object of the class (ie,, the
adress of the memory location where the object is allocated).
‘+ A variable is a reference to a memory location in which an object is stored. To
represent variables and their values we use the following graphical notation.
jao", etc.)
oot
001 Classi ' Classi
last vart [oott vari
sring x 1011 x [Pheto™
010
In
Intvar2 [_25 My[bas var2 [25 ets
an
Typed vara. 7] pot vars?
‘Sting
hello —el reTTTTT]
Fig. 2.3: Reference to object of variable