Bachelor of Information Communication Technology (Hons) Diploma in Information Technology
Academic Year 1
Module Name
Object Oriented Programing I
Module Outline:
1. Introduction to Java Programing Language
2. Introduction to Object Oriented Programing
Table of Contents
JAVA – BASICS
1. Java – Overview I. History of Java II. Tools You Will Need 2. Java - Environment Setup
I. Local Environment Setup II. Popular Java Editors 3. Java – Basic Syntax
I. First Java Program II. Basic Syntax III. Java Identifiers IV. Java Modifiers
V. Java Variables VI. Java Arrays VII. Java Enums VIII. Java Keywords
IX. Comments in Java X. Using Blank Lines
4. Java – Basic Data types I. Primitive Data types II. Reference Data types III. Java Literals
5. Java – Variable Types I. Local Variable II. Instance Variables III. Class/static Variables 6. Java – Modifier Types
I. Java Access Modifiers II. Java Non-Access Modifiers III. The Static Modifier
IV. The Final Modifier V. The Abstract Modifier VI. Access Control Modifier VII. Non-Access Modifiers 7. Java – Basic Operators
I. The Arithmetic Operators II. The Relational Operators III. The Bitwise Operators
IV. The Logical Operators V. The Assignment Operators VI. Miscellaneous Operators VII. Precedence of Java Operators VIII. Associativity of Operators 8. Java – Loop Control
I. While Loop in Java II. for Loop in Java
III. Do While Loop in Java IV. Break Statement in Java
V. Continue Statement in Java VI. Enhanced for loop in Java 9. Java – Decision Making
I. If Statement in Java II. If-else Statement in Java III. The if...else if...else Statement IV. Nested if Statement in Java
V. Switch Statement in Java VI. The ? : Operat
10. Java – Numbers Class
I. Java XXX Value Method II. Java – compareTo() Method III. Java – equals() Method IV. Java – valueOf() Method
V. Java – toString() Method VI. Java – parseInt() Method VII. Java – abs() Method VIII. Java – ceil() Method IX. Java – floor() Method
X. Java – rint() Method XI. Java – round() Method XII. Java – min() Method XIII. Java – max() Method XIV. Java – exp() Method
XV. Java – log() Method XVI. Java – pow() Method XVII. Java – sqrt() Method XVIII. Java – sin() Method
XIX. Java – cos() Method XX. Java – tan() Method XXI. Java – asin() Method XXII. Java – acos() Method XXIII. Java – atan() Method XXIV. Java – atan2() Method
XXV. Java – toDegrees() Method XXVI. Java – toRadians() Metho
11. Java – Character Class I. Escape Sequences II. Java – isLetter() Method III. Java – isDigit() Method
IV. Java – isWhitespace() Method V. Java – isUpperCase() Method VI. Java – isLowerCase() Method VII. Java – toUpperCase() Method VIII. Java – toLowerCase() Method
IX. Java – toString() Method 12. Java – Strings Class
I. Creating Strings
II. Java – String Buffer & String Builder Classes
III. StringBuffer Methods
IV. Java – String Buffer append() Method
V. Java – String Buffer reverse() Method
VI. Java – String Buffer delete() Method
VII. Java – String Buffer insert() Method
VIII. Java – String Buffer replace() Method
IX. String Length
X. Concatenating Strings XI. Creating Format Strings XII. String Methods
XIII. Java – String chartAt() Method XIV. Java – String
compareTo(Object o) Method XV. Java – String compareTo(String
anotherString) Method XVI. Java – String
compareToIgnoreCase() Method
XVII. Java – String concat() Method XVIII. Java – String contentEquals()
Method XIX. Java – String
copyValueOf(char[] data) Method
XX. Java – String
copyValueOf(char[] data, int offset, int count) Method XXI. Java – String endsWith()
Method
XXII. Java – String equals() Method
XXIII. Java – String
equalsIgnoreCase() Method XXIV. Java – String getBytes(String
charsetName) Method
XXV. Java – String getBytes() Method XXVI. Java – String getChars()
Method
XXVII. Java – String hashCode() Method
XXVIII. Java – String indexOf(int ch) Method
XXIX. Java – String indexOf(int ch, int fromIndex) Method
XXX. Java – String indexOf(String str) Method
XXXI. Java – String indexOf(String str, int fromIndex) Method
XXXII. Java – String Intern() Method XXXIII. Java – String lastIndexOf(int ch)
Method
XXXIV. Java – String lastIndexOf(int ch, int fromIndex) Method
XXXV. Java – String lastIndexOf(String str) Method
XXXVI. Java – String lastIndexOf(String str, int fromIndex) Method XXXVII. Java – String length() Method XXXVIII. Java – String matches() Method
XXXIX. Java – String regionMatches() Method
XL. Java – String regionMatches() Method
XLI. Java – String replace() Method XLII. Java – String replaceAll()
Method
XLIII. Java – String replaceFirst() Method
XLIV. Java – String split() Method XLV. Java – String split() Method XLVI. Java – String startsWith()
Method
XLVII. Java – String startsWith() Method
XLVIII. Java – String subsequence() Method
XLIX. Java – String substring() Method
L. Java – String substring() Method
LI. Java – String toCharArray() Method
LII. Java – String toLowerCase() Method
LIII. Java – String toLowerCase() Method
LIV. Java – String toString() Method LV. Java – String toUpperCase()
Method
LVI. Java – String toUpperCase() Method
LVII. Java – String trim() Method LVIII. Java – String valueOf() Method 14. Java – Arrays
I. Declaring Array Variables II. Creating Arrays
III. Processing Arrays IV. The foreach Loops
V. Passing Arrays to Methods VI. Returning an Array from a
Method
VII. The Arrays Class 15. Java – Date & Time
I. Getting Current Date & Time II. Date Comparison
III. Simple Date Format Codes IV. Date and Time Conversion
Characters
V. Parsing Strings into Dates VI. Sleeping for a While VII. Measuring Elapsed Time VIII. Gregorian Calendar Class 16. Java – Regular Expressions
I. Capturing Groups
II. Regular Expression Syntax III. Methods of the Matcher Class 17. Java – Methods
I. Creating Method II. Method Calling III. The void Keyword
IV. Passing Parameters by Value V. Method Overloading
VI. Using Command-Line Argument VII. The Constructors
VIII. Parameterized Constructor IX. The this keyword
X. Variable Arguments(var-args) XI. The finalize( ) Method
18. Java – Files and I/O I. Stream
II. Standard Streams
III. Reading and Writing Files IV. Byte Array Input Stream
V. Data Input Stream VI. File Output Stream
VII. Byte Array Output Stream VIII. Data Output Stream
IX. File Navigation and I/O X. File Class
XI. Directories in Java XII. Listing Directories 19. Java – Exceptions
I. Exception Hierarchy II. Built-in Exceptions III. Exceptions Methods IV. Catching Exceptions V. Multiple Catch Blocks VI. Catching Multiple Type of
Exceptions
VII. The Throws/Throw Keywords VIII. The Finally Block
IX. The try-with-resources X. User-defined Exceptions XI. Common Exceptions 20. Java – Inner Classes
I. Nested Classes
II. Inner Classes (Non-static Nested Classes)
III. Accessing the Private Members
IV. Method-local Inner Class V. Anonymous Inner Class VI. Anonymous Inner Class as
Argument
VII. Static Nested Class
JAVA - OBJECT ORIENTED
21. Java – Objects & Classes I. Objects in Java II. Classes in Java III. Constructors
IV. How to Use Singleton Class V. Creating an Object
VI. Accessing Instance Variables and Method
VII. Source File Declaration Rules VIII. Java Package
IX. Import Statements X. A Simple Case Study 22. Java – Inheritance
I. extends Keyword II. Sample Code III. The super keyword IV. Invoking Superclass
Constructor V. IS-A Relationship
VI. The instanceof Keyword VII. HAS-A relationship VIII. Types of Inheritance 22. Java – Overriding
I. Rules for Method Overriding II. Using the super Keyword 23. Java – Polymorphism
I. Virtual Methods 24. Java – Abstraction
I. Abstract Class
II. Inheriting the Abstract Class III. Abstract Methods
25. Java – Encapsulation
I. Benefits of Encapsulation 26. Java – Interfaces
I. Declaring Interfaces II. Implementing Interfaces III. Extending Interface
IV. Extending Multiple Interfaces V. Tagging Interfaces
27. Java – Packages
I. Creating a Package II. The import Keyword III. The Directory Structure of
Packages
IV. Set CLASSPATH System Variable
Page | 1
01. Java – Overview
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]). Now It is owned by Oracle, and more than 3 billion devices run Java.
The latest release of the Java Standard Edition is Java SE 15. 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.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively.
Java is guaranteed to be Write Once, Run Anywhere.
It is used for:
Mobile applications (specially Android apps)
Desktop applications
Web applications
Web servers and application servers
Games
Database connection
And much, much more Why Use Java?
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most popular programming language in the world
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has a huge community support (tens of millions of developers)
Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs
As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set- top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words.
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).
Page | 2
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 acquisition of Sun Microsystems by Oracle Corporation was completed on January 27, 2010. Significantly, Oracle, previously only a software vendor, now owned both hardware and software product lines from Sun.
Java is:
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
Platform Independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
Architecture-neutral: Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.
Portable: Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.
Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.
Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.
High Performance: With the use of Just-In-Time compilers, Java enables high performance.
Distributed: Java is designed for the distributed environment of the internet.
Page | 3
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time
As of September 2020, Java 8 and 11 are supported as Long Term Support (LTS) versions, and one later non-LTS version is supported. Major release versions of Java, along with their release dates:
Version Date
JDK Beta 1995
JDK1.0 January 23, 1996
JDK 1.1 February 19, 1997
J2SE 1.2 December 8, 1998
J2SE 1.3 May 8, 2000
J2SE 1.4 February 6, 2002
J2SE 5.0 September 30, 2004
Java SE 6 December 11, 2006
Java SE 7 July 28, 2011
Java SE 8 March 18, 2014
Java SE 9 September 21, 2017
Java SE 10 March 20, 2018
Java SE 11 September 25, 2018
Java SE 12 March 19, 2019
Java SE 13 September 17, 2019
Java SE 14 March 17, 2020
Java SE 15 September 15, 2020
Tools You Will Need
For performing the examples discussed in this tutorial, you will need a Pentium 200- MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).
You will also need the following softwares:
Linux or Windows 7 / 8 / 8.1 / 10 operating system Java JDK
Java JRE
Microsoft Notepad or any other text editor
public class MyFirstJavaProgram {
public static void main(String []args) { System.out.println("Hello World");
} }
Page | 4
02. Java – Environment Setup Local Environment Setup
If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine.
Following are the steps to set up the environment.
Java SE is freely available from the link Download Java. You can download a version based on your operating system.
Follow the instructions to download Java and run the .exe to install Java on your machine. Once you installed Java on your machine, you will need to set environment variables to point to correct installation directories:
Setting Up the Path for Windows
Assuming you have installed Java in c:\Program Files\java\jdk directory:
Right-click on 'My Computer' and select 'Properties'.
Click the 'Environment variables' button under the 'Advanced' tab
Now, alter the 'Path' variable so that it also contains the path to the Java executable.
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'
Popular Java Editors
to write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following:
Notepad: On Windows machine, you can use any simple text editor like Notepad, TextPad.
Netbeans: A Java IDE that is open-source and free, which can be downloaded from http://www.netbeans.org/index.html.
Eclipse: A Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/
Page | 5
04. Java – Basic Syntax
When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean.
Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating.
An object is an instance of a class.
Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.
Methods - A method is basically a behavior. A class can contain many methods.
It is in methods where the logics are written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
First Java Program
Let us look at a simple code that will print the words Hello World.
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) { System.out.println("Hello World"); // prints Hello World
} }
Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps:
Open notepad and add the code as above.
Save the file as: MyFirstJavaProgram.java.
Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
Type ‘javac’ MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the
next line (Assumption : The path variable is set).
Page | 6
Now, type 'java MyFirstJavaProgram' to run your program.
You will be able to see ' Hello World ' printed on the window.
C:\> javac MyFirstJavaProgram.java C:\> java MyFirstJavaProgram Hello World
03. Basic Syntax
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name - Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program
Page | 7
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, 1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:
Access Modifiers: default, public , protected, private
Non-access Modifiers: final, abstract, static
Java Enums
Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
For example, if we consider an application for a fresh juice shop, it would be
possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.
Example
class FreshJuice {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE } FreshJuiceSize size;
}
public class FreshJuiceTest {
public static void main(String args[]){ FreshJuice juice = new FreshJuice();
juice.size = FreshJuice.FreshJuiceSize.MEDIUM ; System.out.println("Size: " + juice.size);
} }
Page | 8
The above example will produce the following result:
Size: MEDIUM
Note: Enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.
Java Keywords
The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while
Using Blank Lines
A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it
Page | 9
Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.*/
public static void main(String []args) {
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}
Single-line comment example
Multi-line comment example
public class MyFirstJavaProgram {
public static void main(String []args) {
// This is a comment
System.out.println("Hello World");
} }
public class MyFirstJavaProgram {
public static void main(String []args) {
/* The code below will print the words Hello World to the screen, and it is amazing */
System.out.println("Hello World");
} }
Page | 10
Java Variables
A variable is a piece of memory that can contain a data value. A variable thus has a data type. Data types are covered in more detail in the text on Java data types.
Variables are typically used to store information which your Java program needs to do its job. This can be any kind of information ranging from texts, codes (e.g.
country codes, currency codes etc.) to numbers, temporary results of multi step calculations etc.
Java has two main types of variables Primitive types
are the basic types of data
byte, short, int, long, float, double, boolean, char
primitive variables store primitive values
this types already defined in java Reference types
are any instantiable class as well as arrays
String, Scanner, Random, Die, int[], String[], etc.
reference variables store addresses
User defined class also consider as reference types
In Java, there are different types of Primitive variables, for example:
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127.
short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767
int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.
long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1
float: The float data type is a single-precision 32-bit IEEE 754 floating point
double: The double data type is a double-precision 64-bit IEEE 754 floating point. this data type should never be used for precise values, such as currency.
boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions.
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
Page | 11
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to
32,767
int 4 bytes Stores whole numbers from -2,147,483,648
to 2,147,483,647
long 8 bytes
Stores whole numbers from - 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for
storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for
storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character / letter or ASCII /
Unicode values
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Page | 12
Literals
You may have noticed that the new keyword isn't used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type:
boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;
Integer Literals
An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int.
It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1.
Values of the integral types byte, short, int, and long can be created from int literals.
Values of type long that exceed the range of int can be created from long literals.
Integer literals can be expressed by these number systems:
Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day
Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F
Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later)
For general-purpose programming, the decimal system is likely to be the only number system you'll ever use. However, if you need to use another number system, the following example shows the correct syntax. The prefix 0x indicates hexadecimal and 0b indicates binary:
// The number 26, in decimal
int decVal = 26;
// The number 26, in hexadecimal
int hexVal = 0x1a;
// The number 26, in binary
int binVal = 0b11010;
Page | 13
Floating-Point Literals
A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.
The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).
double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1 = 123.4f;
Character and String Literals
Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as '\u0108' (capital C with circumflex), or
"S\u00ED Se\u00F1or" (Sí Señor in Spanish). Always use 'single quotes' for char literals and "double quotes" for String literals. Unicode escape sequences may be used elsewhere in a program (such as in field names, for example), not just in char or String literals.
The Java programming language also supports a few special escape sequences for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).
There's also a special null literal that can be used as a value for any reference type.
null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String class. This refers to the object (of type Class) that represents the type itself.
Using Underscore Characters in Numeric Literals
In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code.
For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.
Page | 14
The following example shows other ways you can use the underscore in numeric literals:
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;
You can place underscores only between digits; you cannot place underscores in the following places:
At the beginning or end of a number
Adjacent to a decimal point in a floating point literal
Prior to an F or L suffix
In positions where a string of digits is expected
The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:
// Invalid: cannot put underscores // adjacent to a decimal point float pi1 = 3_.1415F;
// Invalid: cannot put underscores // adjacent to a decimal point float pi2 = 3._1415F;
// Invalid: cannot put underscores // prior to an L suffix
long socialSecurityNumber1 = 999_99_9999_L;
// OK (decimal literal) int x1 = 5_2;
// Invalid: cannot put underscores // At the end of a literal
int x2 = 52_;
// OK (decimal literal) int x3 = 5_______2;
// Invalid: cannot put underscores // in the 0x radix prefix
int x4 = 0_x52;
// Invalid: cannot put underscores // at the beginning of a number int x5 = 0x_52;
// OK (hexadecimal literal) int x6 = 0x5_2;
// Invalid: cannot put underscores // at the end of a number
int x7 = 0x52_;
Page | 15
Java Type Casting
Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a smaller size type double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
public class Main {
public static void main(String[] args) { int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0 }
}
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
public class Main {
public static void main(String[] args) { double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9 }
}
Page | 16
05. Java Variable Types
Local Variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.
public class Test { public void pupAge() { int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) { Test test = new Test();
test.pupAge();
} }
This will produce the following result − Puppy age is: 7 Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object in the heap, a slot for each instance variable value is created.
Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must be present throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
Page | 17
Instance Variables
The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.
Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name.
ObjectReference.VariableName.
import java.io.*;
public class Employee {
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName) { name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal) { salary = empSal;
}
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]) {
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
} }
This will produce the following result − name : Ransika , salary :1000.0
Page | 18
Class/Static Variables
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program stops.
Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
values can be assigned in special static initializer blocks.
Static variables can be accessed by calling with the class name ClassName.VariableName.
import java.io.*;
public class Employee {
// salary variable is a private static variable private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) { salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
} }
This will produce the following result − Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT
Page | 19
0.6 Java Modifier Types
Access Modifier
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
Let's understand the access modifiers in Java by a simple table.
Access
Modifier within class within package outside package
by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Page | 20
Non - Access Modifier
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient
For classes, you can use either final or abstract
final: The class cannot be inherited by other classes
abstract: The class cannot be used to create objects For attributes and methods, you can use the one of the following:
final: Attributes and methods cannot be overridden/modified
static: Attributes and methods belongs to the class, rather than an object
abstract: Can only be used in an abstract class, and can only be used on methods.
The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from).
transient: Attributes and methods are skipped when serializing the object containing them
synchronized: Methods can only be accessed by one thread at a time
volatile: The value of an attribute is not cached thread-locally, and is always read from the "main memory"
07. Java Operators
Operators are used to perform operations on variables and values.
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x -- Decrement Decreases the value of a variable by 1 --x
Page | 21
Java Relational / Comparison Operators
Comparison operators are used to compare two values:
Java Logical Operators
Logical operators are used to determine the logic between variables or values:
Operator Name Description Example
&& Logical
and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the
result is true !(x < 5 && x < 10) Java Assignment Operators
Assignment operators are used to assign values to variables.
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Operator Name Example
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Page | 22
Java Bitwise Operators
Bitwise operators are used to perform binary logic with the bits of an integer or long integer.
Operator Description Example Same as Result Decimal
& AND - Sets each bit to 1 if both
bits are 1 5 & 1 0101 & 0001 1 1
| OR - Sets each bit to 1 if any
of the two bits is 1 5 | 1 0101 | 0001 101 5
~ NOT - Inverts all the bits ~ 5 ~0101 1010 10
^ XOR - Sets each bit to 1 if only
one of the two bits is 1 5 ^ 1 0101 ^ 0001 100 4
<<
Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off
9 << 1 1001 << 1 10 2
>>
Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off
9 >> 1 1001 >> 1 1100 12
>>>
Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off
9 >>> 1 1001 >>> 1 100 4
Java Miscellaneous Operators
Ternary or Conditional Operator
Member Access Operator
Comma Operator
Array Index Operator
new Operator
instanceof Operator
Java Ternary or Conditional Operator
Java provides a special operator that is called ternary or conditional operator.
This operator is a set of two symbols that are ? and :. Both symbols collectively form the conditional operator. This operator can be used if we have to initialize or assign a variable on basis of some condition. It follows the below syntax.
expr-1 ? expr-2 : expr-3;
Java Member Access Operator
The Java member access operator is a dot (.) symbol that is used to access data members and member methods of a class by its objects.
Page | 23
Java Comma Operator
Java comma operator is a ',' sign that is used to separate function arguments, and to declare more than one variable of same type in one statement.
Ex.. setName(“Name_1”,”Name_2”,”Name_3”);
Java Array Index Operator
Java array index operator, a set of square brackets ([]), is used to declare and access array elements.
Ex.. array[5];
Java new Operator
The Java new operator is used to create a new object. Operator new is a Java keyword. It is followed by a call to a constructor, which initializes the new object.
Note that declaring an object and creating an object are two different things.
Simply declaring a reference variable does not create an object. For that, we need to use the new operator. The new operator creates an object by allocating memory to it and returns a reference to that memory location. The Java new operator needs a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. Following piece of code demonstrates the use of new operator.
Ex.. Student student = new Student(“Akila”);
Java instanceof Operator
Java instanceof operator also called type comparison operator compares an object to a specific type. It follows the syntax objRef instanceof type. Here objRef is the object name and the type is the name of object type whom objRef will be compared to. The equals() method of Java is a nice example that uses instanceof operator to check if two objects are equal. The following example (InstanceOfDemo.java) shows the use of Java instanceof operator.
Ex.. Child class name instanceof Human Class Precedence of Java Operator
int myInt = 12 - 4 * 2;
What will be the value of myInt? Will it be (12 - 4)*2, that is, 16? Or it will be 12 - (4 * 2), that is, 4?
When two operators share a common operand, 4 in this case, the operator with the highest precedence is operated first.
In Java, the precedence of * is higher than that of -. Hence, the
multiplication is performed before subtraction, and the value of myInt will be 4.
Page | 24
Operator Precedence Table
The table below lists the precedence of operators in Java; higher it appears in the table, the higher its precedence.
Operators Precedence
postfix increment and decrement ++ -- prefix increment and decrement, and
unary ++ -- + - ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Page | 25
Associativity of Operators
If an expression has two operators with similar precedence, the expression is
evaluated according to its associativity (either left to right, or right to left). Let's take an example.
a = b = c;
Here, the value of c is assigned to variable b. Then the value of b is assigned of variable a. Why? It's because the associativity of = operator is from right to left.
The table below shows the associativity of Java operators along with their associativity.
Operators Precedence Associativity
postfix increment and decrement ++ -- left to right
prefix increment and decrement,
and unary ++ -- + - ~ ! right to left
multiplicative * / % left to right
additive + - left to right
shift << >> >>> left to right
relational < > <= >= instanceof left to right
equality == != left to right
bitwise AND & left to right
bitwise exclusive OR ^ left to right
bitwise inclusive OR | left to right
logical AND && left to right
logical OR || left to right
ternary ? : right to left
assignment = += -= *= /= %=
&= ^= |= <<= >>= >>>= right to left
You don't need to memorize everything here. Most of the time, the precedence and associativity of operators makes sense in itself.
Page | 26
08. Java – Loop Control
While loop
Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax:
while (test_expression) {
// statements
update_expression;
}
The various parts of the While loop are:
Test Expression (Guard Condition) : In this expression we have to test the condition.
If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the while loop.
Example:
i <= 10
Page | 27
Update Expression : After executing the loop body, this expression increments/decrements the loop variable by some value.
Example:
i++;
How does a While loop executes?
1. Control falls into the while loop.
2. The flow jumps to Condition 3. Condition is tested.
4. If Condition yields true, the flow goes into the Body.
5. If Condition yields false, the flow goes outside the loop 6. The statements inside the body of the loop get executed.
7. Updating takes place.
8. Control flows back to Step 2.
9. The do-while loop has ended and the flow has gone outside.
// Java program to illustrate while loop.
class whileLoopDemo {
public static void main(String args[]) {
// initialization expression int i = 1;
// test expression while (i < 6) {
System.out.println("Hello World");
// update expression i++;
} } }
Output:
Hello World Hello World Hello World Hello World Hello World
Page | 28
For loop in Java
As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this the control flow, or the flow of execution of the program.
for loop Java
First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re- evaluated.
Page | 29
// Java program to illustrate while loop.
class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
} } }
The output of this program is:
The value of i is: 10 The value of i is: 9 The value of i is: 8 The value of i is: 7 The value of i is: 6 The value of i is: 5 The value of i is: 4 The value of i is: 3 The value of i is: 2
Do while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.
If the Boolean expression is true, the control jumps back up to do statement,
and the statements in the loop execute again.
This process repeats until the Boolean expression is false.
Page | 30 public class Test {
public static void main(String args[]) { int x = 10;
do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
} while( x < 5 );
} }
This will produce the following result – value of x : 10
value of x : 11 value of x : 12 value of x : 13 value of x : 14 Enhanced for loop
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays.
Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
public class Test {
public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) { System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
} }
This will produce the following result − 10, 20, 30, 40, 50
Page | 31
loop control statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Java supports the following control statements. Click the following links to check their detail.
No. Control Statement & Description
1
break statement
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
2
continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating
Break statement in java
The break statement in Java programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
The syntax of a break is a single statement inside any loop − break;
public class Test {
public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) { if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
} } }
Page | 32
Continue statement in java
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes control to immediately jump to the update statement.
In a while loop or do/while loop, control immediately jumps to the Boolean expression.
The syntax of a continue is a single statement inside any loop − continue;
public class Test {
public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) { if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
} } }
Enhanced for loop in Java
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays.
for(declaration : expression) { // Statements
}
Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Page | 33
Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array
public class Test {
public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) { System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) { System.out.print( name );
System.out.print(",");
} } }