Java Programming Basics and Tools Guide
Java Programming Basics and Tools Guide
1 Introduction, the Java Language Specification, API, JDK, IDE, Creating, Compiling
Introduction:
Java is a class-based, object-oriented programming language that is designed to have as few
implementation dependencies as possible. It is intended to let application developers write
once, and run anywhere (WORA), meaning that compiled Java code can run on all platforms
that support Java without the need for recompilation. Java was first released in 1995 and is
widely used for developing applications for desktop, web, and mobile devices. Java is known
for its simplicity, robustness, and security features, making it a popular choice for enterprise-
level applications.
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995 and later
acquired by Oracle Corporation. It is a simple programming language. Java makes writing,
compiling, and debugging programming easy. It helps to create reusable code and modular
programs. Java is a class-based, object-oriented programming language and is designed to
have as few implementation dependencies as possible. A general-purpose programming
language made for developers to write once run anywhere that is compiled Java code can
run on all platforms that support Java. Java applications are compiled to byte code that can
run on any Java Virtual Machine.
History:
Java’s history is very interesting. It is a programming language created in 1991. James
Gosling, Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green
team initiated the Java language in 1991. Sun Microsystems released its first public
implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular platforms.
Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its
specifications. With the arrival of Java 2, new versions had multiple configurations built for
different types of platforms.
In 1997, Sun Microsystems approached the ISO standards body and later formalized Java, but
it soon withdrew from the process. At one time, Sun made most of its Java implementations
available without charge, despite their proprietary software status. Sun generated revenue
from Java through the selling of licenses for specialized products such as the Java Enterprise
System.
On November 13, 2006, Sun released much of its Java virtual machine as free, open-source
software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code
available under open-source distribution terms.
The principles for creating java were simple, robust, secured, high-performance,
portable, multi-threaded, interpreted, dynamic, etc. In 1995 Java was developed by
James Gosling, who is known as the Father of Java. Currently, Java is used in mobile
devices, internet programming, games, e-business, etc.
What is API?
Computer languages have strict rules of usage. If you do not follow the rules when writing a
program, the computer will not be able to understand it! An API defines and specifies such rules.
API stands for Application Programming Interface. According to the Wikipedia, an API defines
interactions between multiple software intermediaries. It defines the kinds of calls or requests
that can be made, how to make them, the data formats that should be used, the conventions to
follow, etc. It can also provide extension mechanisms so that users can extend existing
functionality in various ways and to varying degrees.
The Java API is a library of pre-written classes, that are free to use, included in the Java
development [Link] library contains components for managing input, database
programming, and much much more. .
What is JDK?
The Java Development Kit (JDK) is a basic set of tools used for developing Java applications
and applets. JDK comes from Oracle, the owner of Java, and it contains a compiler, an
interpreter, the Applet Viewer program, other utility programs, the standard Java library,
documentation, and examples.
Java is a very powerful language that can be used in many ways. It comes in three editions:
Java Standard Edition (Java SE) to develop client – side applications. The applications can
run standalone or as applets running from a web browser.
Java Enterprise Edition (Java EE) to develop server – side applications.
Java Micro Edition (Java ME) to develop applications for mobile devices.
In this course, we use Java SE to introduce Java programming. There are many versions of Java
SE. To prepare for the AP Computer Science A exam, we choose to use Java SE 8. You need to
download JDK 1.8, also known as Java 8 or JDK 8.
What is JRE?
The program for running Java program is known as JRE (Java Runtime Environment). The JRE
is a subset of JDK. The following diagram shows the relationship among JDK, JRE and JVM
(Java Virtual Machine, please refer to the previous lesson if you don’t remember it).
What is IDE?
Once JDK is downloaded and installed, you can enter Java program from a command line,
compile, test and run it. The command line is pretty cool but not so user friendly especially for
beginners. Instead of using the JDK, you can also download and install a Java Development tool
like Eclipse, NetBeans, DrJava and TextPad – software that provides an Integrated Development
Environment (IDE) for developing Java programs quickly. These software provide graphical user
interface (GUI) that greatly enhance user experience.
You can use any text editor or IDE to create and edit a Java source-code file. In this article, I
demonstrate how to create, compile, and run Java programs from a command window.
[Link]
javac [Link]
If there aren’t any syntax errors, the compiler generates a bytecode file with a .class extension.
Thus, this command generates a file named [Link].
java Welcome
The output of the above program displays the message “Welcome to Java!”
1.2 Executing a Java Program Developing Java Programs Using Net Beans/J Creator
For the first application, HelloWorldApp, will simply display the greeting "Hello World!" To
create this program, we will:
When you create an IDE project, you create an environment in which to build and run
your applications. Using IDE projects eliminates configuration issues normally associated
with developing on the command line. You can build or run your application by choosing
a single menu item within the IDE.
A source file contains code, written in the Java programming language, that you and
other programmers can understand. As part of creating an IDE project, a skeleton source
file will be automatically generated. You will then modify the source file to add the
"Hello World!" message.
The IDE invokes the Java programming language compiler (javac), which takes your
source file and translates its text into instructions that the Java virtual machine can
understand. The instructions contained within this file are known as bytecodes.
The IDE invokes the Java application launcher tool (java), which uses the Java virtual
machine to run your application.
3. In the New Project wizard, expand the Java category and select Java Application as
shown in the following figure:
4. In the Name and Location page of the wizard, do the following (as shown in the figure
below):
o In the Project Name field, type Hello World App.
o In the Create Main Class field, type [Link].
NetBeans IDE, New Project wizard, Name and Location page.
5. Click Finish.
The project is created and opened in the IDE. You should see the following components:
The Projects window, which contains a tree view of the components of the project,
including source files, libraries that your code depends on, and so on.
The Source Editor window with a file called [Link] open.
The Navigator window, which you can use to quickly navigate between elements within
the selected class.
NetBeans IDE with the HelloWorldApp project open.
It may be necessary to add JDK 8 to the IDE's list of available platforms. To do this, choose
Tools | Java Platforms as shown in the following figure:
Selecting the Java Platform Manager from the Tools Menu
If you don't see JDK 8 (which might appear as 1.8 or 1.8.0) in the list of installed platforms,
click Add Platform, navigate to your JDK 8 install directory, and click Finish. You should now
see this newly added platform:
To specify this JDK for the current project only, select Hello World App in the Projects pane,
choose File | Project Properties (Hello World App), click Libraries, then select JDK 1.8 in
the Java Platform pulldown menu. You should see a screen similar to the following:
When you created this project, you left the Create Main Class checkcbox selected in the New
Project wizard. The IDE has therefore created a skeleton class for you. You can add the "Hello
World!" message to the skeleton code by replacing the line:
/**
*
* @author
*/
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
These four lines are a code comment and do not affect how the program runs. Later sections of
this tutorial explain the use and format of code comments.
Note: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and
launcher (java) are case-sensitive, so you must capitalize consistently.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworldapp;
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
public class HelloWorldApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
[Link]("Hello World!"); // Display the string.
}
}
Compile the Source File into a .class File
To compile your source file, choose Run | Build Project (Hello World App) from the IDE's
main menu.
The Output window opens and displays output similar to what you see in the following figure:
If the build output concludes with the statement BUILD SUCCESSFUL, congratulations! You
have successfully compiled your program!
If the build output concludes with the statement BUILD FAILED, you probably have a syntax
error in your code. Errors are reported in the Output window as hyperlinked text. You double-
click such a hyperlink to navigate to the source of an error. You can then fix the error and once
again choose Run | Build Project.
When you build the project, the bytecode file [Link] is generated. You can see
where the new file is generated by opening the Files window and expanding
the Hello World App/build/classes/helloworldapp node as shown in the following figure.
Files window, showing the generated .class file.
Now that you have built the project, you can run your program.
From the IDE's menu bar, choose Run | Run Main Project.
The program prints "Hello World!" to the Output window (along with other output from the
build script)
1.2.2 Developing Java Programs Using J Creator
You will then see a window entitled "JCreator - [Start Page]" ...
2. If you see the "Tip of the Day" window, close it.
NOTE:
The Location, Source Path and Output paths
will be automatically filled in according to how the
JCreator software was originally set up.
The following screen just shows an example.
prog_01 - JCreator
Close the File View and Package View windows for now,
just leaving the source code (prog_01.java)
and General Output windows open.
/**
* @(#)prog_01.java
*
* prog_01 application
*
* @author
* @version 1.00 2007/9/9
*/
Process completed.
Process completed.
1.3 Identifiers, Variables, Assignment Statements and Assignment Expressions
In Java programming, identifiers are essential because they let programmers efficiently reference
and modify program parts. A class identifier uniquely identifies a class definition to enable the
production of objects and the calling of class methods, for example. In a similar vein, method
IDs designate executable code blocks, and variable identifiers stand in for storage locations
connected to data values.
Identifiers in Java are symbolic names used for identification. It can be a class name, variable
name, method name, package name, constant name, and other names used in programming.
However, in Java, some reserved words cannot be used as an identifier.
For every identifier, some conventions should be used before declaring them. Let's understand it
with a simple Java program:
Importance of Identifiers
1. Programme Structure: Classes, variables, methods, packages, and other things are named
by identifiers that are the fundamental building blocks of Java programmes.
2. Readability and Understanding: When well-chosen identifiers improve the readability
and comprehensibility of code, developers can more easily comprehend the function and
goal of various program components.
3. Modifiability: By offering a simple method of referencing and altering program elements,
identifiers aid in code maintenance and change.
4. Communication: Identifiers allow developers to communicate with each other by sharing
details about the purpose and capabilities of certain program pieces.
o A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore
(_) or a dollar sign ($). For example, @javatpoint is not a valid identifier because it
contains a special character @.
o There should not be any space in an identifier. For example, java tpoint is an invalid
identifier.
o An identifier should not contain a number at the starting. For example, 123javatpoint is
an invalid identifier.
o An identifier should be of length 4-15 letters only. However, there is no limit on its
length. But, it is good to follow the standard conventions.
o We cannot use the Java reserved keywords as an identifier such as int, float, double, char,
etc. For example, int double is an invalid identifier in Java.
o An identifier should not be any query language keywords such as SELECT, FROM,
COUNT, DELETE, etc.
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
boolean - stores values with two states: true or false
To create a variable, you must specify the type and assign it a value:
Syntax
Where type is one of Java's types (such as int or String), and variableName is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value "John".
Then we use println() to print the name variable:
[Link](name);
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
[Link](myNum);
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
[Link](myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
[Link](myNum);
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword (this
will declare the variable as "final" or "constant", which means unchangeable and read-only):
Example
myNum = 20; // will generate an error: cannot assign a value to a final variable
Other Types
Example
int myNum = 5;
An assignment statement designates a value for a variable. An assignment statement can be used
as an expression in Java.
After a variable is declared, you can assign a value to it by using an assignment statement. In
Java, the equal sign = is used as the assignment operator. The syntax for assignment statements is
as follows:
variable = expression;
An expression represents a computation involving values, variables, and operators that, when
taking them together, evaluates to a value. For example, consider the following code:
You can use a variable in an expression. A variable can also be used on both sides of
the = operator. For example:
x=x+1
In the above assignment statement, the result of x + 1 is assigned to the variable x. Let’s say
that x is 1 before the statement is executed, and so becomes 2 after the statement execution.
To assign a value to a variable, you must place the variable name to the left of the assignment
operator. Thus the following statement is wrong:
1 = x; // Wrong
In Java, an assignment statement is an expression that evaluates a value, which is assigned to the
variable on the left side of the assignment operator. Whereas an assignment expression is the
same, except it does not take into account the variable.
That’s why the following statements are legal:
[Link](x = 1);
x=1;
[Link](x);
//If a value is assigned to multiple variables, you can use this syntax:
i = j = k = 1;
is equivalent to:
k = 1;
j = k;
i = j;
Note: The data type of a variable on the left must be compatible with the data type of a value on
the right. For example, int x = 1.0 would be illegal, because the data type of x is int (integer) and
does not accept the double value 1.0 without Type Casting.
1.4 Named Constants, Naming Conventions. Numeric Data Types and Operations, Numeric
Literals
1.4.1 Named Constants
A named constant is an identifier that represents a permanent value. The value of a variable may
change during the execution of a program, but a named constant, or simply constant, represents
permanent data that never changes. For example, pie of a circle is a constant. If you use it
frequently, you don’t want to keep typing 3.14159; instead, you can declare a constant for pie.
Here is the syntax for declaring a constant:
A constant must be declared and initialized in the same statement. The word final is a Java
keyword for declaring a constant.
You don’t have to repeatedly type the same value if it is used multiple times;
If you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to
change it only in a single location in the source code;
A descriptive name for a constant makes the program easy to read.
But, it is not forced to follow. So, it is known as convention not rule. These conventions are
suggested by several Java communities such as Sun Microsystems and Netscape.
All the classes, interfaces, packages, methods and fields of Java programming language are given
according to the Java naming convention. If you fail to follow these conventions, it may generate
confusion or erroneous code.
Java has six numeric types for integers and floating-point numbers with operators +, -, *, /, and
%.
Numeric Types
Every data type has a range of values. The compiler allocates memory space for each variable or
constant according to its data type. Java provides eight primitive data types for numeric values,
characters, and Boolean values.
Java uses four types for integers: byte, short, int, and long. Choose the type that is most
appropriate for your variable. For example, if you know an integer stored in a variable is within a
range of a byte, declare the variable as a byte.
Java uses two types for floating-point numbers: float and double. The double type is twice as big
as float, so the double is known as double precision and float as single precision. Normally, you
should use the double type, because it is more accurate than the float type.
Reading Numbers from the Keyboard
Here are examples for reading values of various types from the keyboard:
If you enter a value with an incorrect range or format, a runtime error would occur.
Numeric Operators
The operators for numeric data types include the standard arithmetic operators: addition (+),
subtraction (–), multiplication (****), division (/), and remainder (%*).
When both operands of a division are integers, the result of the division is the quotient and the
fractional part is truncated. For example, 5 / 2 yields 2, not 2.5, and –5 / 2 yields -2, not –2.5. To
perform a float-point division, one of the operands must be a floating-point number. For
example, 5.0 / 2 yields 2.5.
The % operator, known as remainder or modulo operator, yields the remainder after division.
The operand on the left is the dividend and the operand on the right is the divisor. Therefore, 7 %
3 yields 1, 3 % 7 yields 3, 12 % 4 yields 0, 26 % 8 yields 2, and 20 % 13 yields 7.
The % operator is often used for positive integers, but it can also be used with negative integers
and floating-point values. The remainder is negative only if the dividend is negative. For
example, -7 % 3 yields -1, -12 % 4 yields 0, -26 % -8 yields -2, and 20 % -13 yields 7.
Remainder is very useful in programming. For example, an even number % 2 is always 0 and an
odd number % 2 is always 1. Thus, you can use this property to determine whether a number is
even or odd. If today is Saturday, it will be Saturday again in 7 days. Suppose you and your
friends are going to meet in 10 days. What day is in 10 days? You can find that the day is
Tuesday using the following expression:
(6 + 10) % 7 is 2
The program obtains minutes and remaining seconds from an amount of time in seconds. For
example, 500 seconds contains 8 minutes and 20 seconds.
The + and - operators can be both unary and binary. A unary operator has only one operand;
a binary operator has two. For example, the - operator in -5 is a unary operator to negate
number 5, whereas the - operator in 4 - 5 is a binary operator for subtracting 5 from 4.
Exponent Operations
The [Link](a, b) method can be used to compute a^b. The pow method is defined in
the Math class in the Java API. You invoke the method using the syntax [Link](a,
b) (e.g., [Link](2, 3)), which returns the result of a^b (2^3). Here, a and b are parameters for
the pow method and the numbers 2 and 3 are actual values used to invoke the method. For
example,
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:
o Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may
have a positive (+) or negative (-) Note that between numbers commas and non-digit
characters are not permitted. For example, 5678, +657, -89, etc.
1. int decVal = 26;
o Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For
example, 045, 026,
1. int octVal = 067;
o Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create
binary literals in Java SE 7 and later). Prefix 0b represents the Binary system. For
example, 0b11010.
1. int binVal = 0b11010;
Real Literals
The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.
Backslash Literals
Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:
Character Literals
A character literal is expressed as a character or an escape sequence, enclosed in a single quote
('') mark. It is always a type of char. For example, 'a', '%', '\u000d', etc.
String Literals
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It
may be alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345",
"\n", etc.
o Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It is
a 32-bit float literal.
o Floating-point literals for double type end with D or d. It is optional to write D or d. For
example, 6d, 8.354D, etc. It is a 64-bit double literal.
o It can also be represented in the form of the exponent.
Floating:
Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0 and 1. For
example, true, 0, etc.
1. float g = 6_.674f;
2. float g = 6._674F;
3. long phoneNumber = 99_00_99_00_99_L;
4. int x = 77_;
5. int y = 0_x76;
6. int z = 0X_12;
7. int z = 0X12_;
1.5 Evaluating Expressions and Operator Precedence, Increment and Decrement
Operators, Numeric Type Conversions
In real life when we solve an expression containing multiple operators we follow some rules. For
example in an expression 2+3*4, we do the multiplication first before addition because the
multiplication operator has higher precedence than addition operator. The same applies in java as
well.
In java, operator precedence is a rule that tells us the precedence of different operators. Operators
with higher precedence are evaluated before operators with lower precedence. For example in
expression a+b*c, the operator * will be evaluated before + operator, because operator * has
higher precedence than + operator.
Table bellow shows the precedence of operators in decreasing order, the operators appearing first
in table have higher precedence than operators appearing later. Operators appearing in same row
of table have equal precedence. When operators of equal precedence appears in the same
expression, a rule governs the evaluation order which says that all binary operators except for the
assignment operator are evaluated from left to right while assignment operator is evaluated from
right to left. For example in expression 2+3-4, 2 and 3 is added first then 4 is subtracted from it.
Consider a and b as two operands for the examples given in below table.
Logical OR || a||b
Ternary ?: a = a>2 ? a : b
The postfix operator(eg. a++, a--) has the highest precedence in java.
Assignment operator and it's different forms has the lowest precedence in java.
The operands of operators are evaluated from left to right. For example in expression ++a + b--,
the operand ++a is evaluated first then b-- is evaluated.
Every operand of an operator (except the conditional operators &&, ||, and ? :) are evaluated
completely before any part of the operation itself is performed. For example in expression ++a
+ b--, the addition operation will take place only after ++a and b-- is evaluated.
The left-hand operand of a binary operator are evaluated completely before any part of the
right-hand operand is evaluated.
All binary operators are evaluated from left to right except assignment operator.
Parentheses "()" are used to alter the order of evaluation. For example in an expression a+b*c, if
you want the addition operation to take place first, then rewrite the expression as (a+b)*c.
class OperatorPrecedence {
int result = 0;
result = 5 + 2 * 3 - 1;
result = 5 + 4 / 2 + 6;
result = 3 + 6 / 2 * 3 - 1 + 2;
result = 6 / 2 * 3 * 2 / 3;
int x = 2;
Output:
5 + 2 * 3 - 1 = 10
5 + 4 / 2 + 6 = 13
3 + 6 / 2 * 3 - 1 + 2 = 13
6 / 2 * 3 * 2 / 3 = 6
result = 2
Let's understand how the last expression x++ + x++ * --x / x++ - --x + 3 >> 1 | 2 is evaluated
step by step.
2 + 3 * 3 / 3 - 3 + 3 >> 1 | 2
* and / have higher preference than other, * evaluated first as it comes in left
2 + 9 / 3 - 3 + 3 >> 1 | 2
2 + 3 - 3 + 3 >> 1 | 2
5 >> 1 | 2
2|2
Output
2
1.5.2 Increment and Decrement Operators
Java programming language is well known for its simplicity and readability. One of the features
that contribute to this simplicity is the use of various operators. Among these operators are the
increment (++) and decrement (–) operators, which are used to increase or decrease the value of
a variable by 1. In this blog post, we will discuss these operators in detail and explore their use
cases with examples. Whether you are a beginner or an intermediate developer, this post will
help you understand the concept of increment and decrement operators in Java.
The increment (++) and decrement (–) operators are unary operators in Java, which means they
operate on a single operand. They are used to increase or decrease the value of an integer,
floating-point, or character variable by 1. These operators can be applied in two ways: prefix and
postfix.
In the prefix form, the operator is placed before the operand. The value of the operand is
incremented or decremented first, and then the result is used in the expression. The syntax for
prefix increment and decrement operators is as follows:
++variable;
--variable;
In the postfix form, the operator is placed after the operand. The value of the operand is used in
the expression first, and then it is incremented or decremented. The syntax for postfix increment
and decrement operators is as follows:
variable++;
variable--;
Now, let's dive deeper into these operators and see how they work with examples.
Let's start with a simple example to understand the prefix increment operator.
int a = 5;
int b = ++a;
[Link]("a: " + a + ", b: " + b);
In this example, the value of a is incremented by 1, and then the result is assigned to b. The
output will be:
a: 6, b: 6
int a = 5;
int b = a++;
[Link]("a: " + a + ", b: " + b);
In this example, the value of a is used in the expression first, and then it is incremented by 1. The
output will be:
a: 6, b: 5
int a = 5;
int b = --a;
[Link]("a: " + a + ", b: " + b);
In this example, the value of a is decremented by 1, and then the result is assigned to b. The
output will be:
a: 4, b: 4
int a = 5;
int b = a--;
[Link]("a: " + a + ", b: " + b);
In this example, the value of a is used in the expression first, and then it is decremented by 1.
The output will be:
a: 4, b: 5
Increment and decrement operators are commonly used in loops and other control structures.
They can simplify the code and make it more readable.
Using Increment Operator in a Loop
For instance, you can use the increment operator in a for loop to iterate through an array.
In this example, the variable i is incremented by 1 in each iteration of the loop until it reaches the
length of the array.
Similarly, you can also use the decrement operator in a loop to iterate through an array in reverse
order.
In this example, the variable i is decremented by 1 in each iteration of the loop until it reaches 0.
1.5.3 Numeric Type Conversions
Floating-point numbers can be converted into integers using explicit casting. If an integer and a
floating-point number are involved in a binary operation, Java automatically converts the integer
to a floating-point value. So, 3 * 4.5 is same as 3.0 * 4.5.
You can always assign a value to a numeric variable whose type supports a larger range of
values; thus, for instance, you can assign a long value to a float variable. You cannot, however,
assign a value to a variable of a type with a smaller range unless you use type casting. Casting is
an operation that converts a value of one data type into a value of another data type. Casting a
type with a small range to a type with a larger range is known as widening a type. Casting a type
with a large range to a type with a smaller range is known as narrowing a type. Java will
automatically widen a type, but you must narrow a type explicitly.
The syntax for casting a type is to specify the target type in parentheses, followed by the
variable’s name or the value to be cast. For example, the following statement
[Link]((int)1.7);
displays 1. When a double value is cast into an int value, the fractional part is truncated. The
following statement
[Link]((double)1 / 2);
displays 0.5, because 1 is cast to 1.0 first, then 1.0 is divided by 2. However, the statement
[Link](1 / 2);
displays 0, because 1 and 2 are both integers and the resulting value should also be an integer.
Casting is necessary if you are assigning a value to a variable of a smaller type range, such as
assigning a double value to an int variable. A compile error will occur if casting is not used in
situations of this kind. However, be careful when using casting, as loss of information might lead
to inaccurate results.
Casting does not change the variable being cast. For example, d is not changed after casting in
the following code:
double d = 4.5;
int i = (int)d; // i becomes 4, but d is still 4.5
To assign a variable of the int type to a variable of the short or byte type, explicit casting must
be used. For example, the following statements have a compile error:
int i = 1;
byte b = i; // Error because explicit casting is required
However, so long as the integer literal is within the permissible range of the target variable,
explicit casting is not needed to assign an integer literal to a variable of the short or byte type
UGCSA117 : Object-Oriented Programming(OOP)
in Java
(BCA 2nd Sem)
Unit-2
Module2.1:
2.1.1 Boolean Data Type
The Boolean data type is used to store logic values i.e. truth values which are true
or false. It takes only 1 byte of space to store logic values. Here, true means 1,
and false means 0. In the Boolean data type any value other than ‘0’ is considered
as ‘true’. Boolean values are most commonly used in data structures to decide the
flow of control of a program and decision statements. In programming languages,
we have various data types to store different data types. The most used data types
are integer, string, float, and Boolean. The Boolean data type is a type of data that
stores only two types of values i.e. True or False. These values are not case-
sensitive depending upon programming languages. The name Boolean comes
from the branch of mathematics called Boolean algebra, named after George Bool
the mathematician.
[Link]("a: "+a);
[Link]("b: "+b);
}
}
2.1.2Difference Between Boolean and Other Data Types
In programming languages, there are three types of data which are Booleans, Text,
and Numbers. It is important to understand the differences between them and some
basics about them.
Booleans: They are either true (1) or false (0) and take only 1 byte of space in
memory. while other data types take 2 to 8 bytes depending on the machine.
Numbers: Numbers can be negative, positive, and zero or decimal numbers. The data
type used to store numbers such as short, int, and double can take 2 to 8 bytes of
space in memory.
Text: Text includes characters, alphabets, numbers, and a collection of them. Text can
be of character or string type. The size of 1 character is 2 bytes.
2.1.3 If Else Statement in Programming
An if else statement in programming is a basic programming technique
that allows you to make decisions based on certain conditions. It allows
your program to execute different pieces of code depending on whether
the specified condition evaluates to true or false. This capability is
crucial in building dynamic and functional applications.
2.1.4 Importance of If Else Statement:
The importance of if-else statements lies in their ability to control the execution
of a program. Using if-else statements allows developers to apply logic that
responds to situations, making programs more versatile and powerful. Whether
manipulating user statements, manipulating data, or controlling program flow, if-
else statements play an important role in programming.
2.1.5 Basic Syntax of If Else Statement:
Generally, the basic syntax of if false statements follow this pattern: if
(condition) {
// Code block to execute if condition is true }
else {
// Code block to execute if condition is false }
In this syntax:
The `if` keyword begins a conditional statement.
The condition is enclosed in parentheses `()`.
If the condition evaluates to true, the code block immediately following the `if`
statement is executed.
If the condition evaluates to false, the code block is executed in the `else`
statement.
2.1.6 If Else Statement in Java:
Here is the implementation of if-else statement in Java language:
if (num > 0)
[Link]("Number is positive.");
} else {
[Link]("Number is non-positive.");
} }
}
if (num > 0) {
[Link]("Number is positive.");
// Nested if-else statement to check if num is even or odd
if (num % 2 == 0) {
[Link]("Number is even.");
} else {
[Link]("Number is odd.");
} else {
[Link]("Number is non-positive.");
} }
Syntax of Nested if
if (condition1) { if
(condition2) { if
(condition3) {
// statements;
}
}
}
Note: If the outer condition satisfies then only the inner condition will be checked.
Along with if condition, else condition can also be executed.
UGCSA117 : Object-Oriented Programming(OOP)
in Java
(BCA 2nd Sem)
Unit-2
Module2:
For OR Operator:
Condition 1: c > a
Condition 2: c > b
Output:
True [Both Conditions are true]
For OR Operator:
Condition 1: c > a
Condition 2: c > b
Output:
True [One of the Condition if true]
Note: Java switch expression must be of byte, short, int, long(with its Wrapper
type), Enums, and string. Beginning with JDK7, it also works with enumerated
types (Enums in Java), the String class, and Wrapper classes.
Syntax: switch(expression)
{ case value1 :
// Statements
break; // break is optional
case value2 : //
Statements break; //
break is optional
....
....
....
default :
// default Statement
}
2.2.1.1Some Important Rules for Java Switch Statements
Case values must be constants or literals and of the same type as the switch
expression.
Duplicate case values are not allowed.
The break statement is used to exit from the switch block. It is optional but
recommended to prevent fall-through.
The default case is optional and executes if no case matches the switch
expression. It can appear anywhere within the switch block.
Note: Starting from Java 7, switch statements can use String-type values.
They can also handle wrapper classes like Integer, Short, Byte, Long.
Flowchart of Switch-Case Statement
This flowchart shows the control flow and working of switch statements:
Note: Java switch statement is a fall-through statement that means it executes all
statements if break keyword is not used, so it is highly essential to use break
keyword inside each case.
Op
Prece era Descri Assoc
dence tor ption iativity
1 () Parenth Left-
eses toRight
(functi
on call)
When various operators are used within the same statement a problem arises which
is which operation should be performed first. To solve this problem there is the
concept of operator precedence. Operator Precedence is a set of rules that defines
the priority for all the operators present in a programming language. The operation
which has an operator with the highest priority will be executed first. Operator
Associativity:
If we have operators which have same precedence in the same statement then we
use associativity to figure out which operation should be performed first.
Associativity defines whether you should go from left to right or you should go
to right to left. If Associativity says that you should go left to right then
operation on the left side should be performed first and then only, we should
move to right side.
[] Array
Subscri
pt
(Square
Bracket
s)
. Dot
Operat
or
-> Structu
re
Pointer
Operat
or
++ , Postfix
— increm
ent,
decrem
ent
2 ++ / Prefix Rightto-
— increm Left
ent,
decrem
ent
Op
Prece era Descri Assoc
dence tor ption iativity
+/ Unary
– plus,
minus
!,~ Logical
NOT,
Bitwise
comple
ment
Cast
(typ
Operat
e)
or
* Derefer
ence
Operat
or
& Addres
sof
Operat
or
size Determ
of ine size
in bytes
Op
Prece era Descri Assoc
dence tor ption iativity
Bitwise
<< , shift Left-
>> left, toRight
5
Bitwise
shift
right
6 <, Relatio Left-
<= nal less toRight
than,
less
than or
equal
to
Relatio
>,
nal
>=
greater
Op
Prece era Descri Assoc
dence tor ption iativity
than,
greater
than, or
equal
to
7 == , Relatio Left-
!= nal is toRight
equal
to, is
not
equal
to
9 ^ Bitwise Left-
exclusi toRight
ve OR
10 | Bitwise Left-
inclusi toRight
ve OR
12 || Logical Left-
OR toRight
13 Ternary Rightto-
?:
conditi Left
onal
14 = Assign Rightto-
ment Left
+= , - Additio
= n,
subtrac
tion
assign
ment
Multipl
ication,
*= , divisio
/= n
assign
ment
%= Modulu
, s,
&= bitwise
AND
Op
Prece era Descri Assoc
dence tor ption iativity
assign
ment
Bitwise
exclusi
^= , ve,
|= inclusi
ve OR
assign
ment
<<= Bitwise
, shift
>>= left,
right
assign
ment
15 , comma Left-
(expres toRight
sion
separat
or)
UGCSA117 : Object-Oriented Programming(OOP)
in Java (BCA 2nd Sem)
Unit-2
Module2:
2.3 Java Math Class
[Link] Class methods help to perform numeric operations like square, square root,
cube, cube root, exponential, and trigonometric operations.
Methods of Math Class in Java
Math class consists of methods that can perform mathematical operations and
can make long calculations a bit easier. Let us check the method provided in the
Math class.
Method Description
MODULE-2:
2.4 Character Class in Java
Java provides a wrapper class Character in [Link] package. An object of type
Character contains a single field, whose type is char. The Character class offers
several useful class (i.e., static) methods for manipulating characters. You can
create a Character object with the Character constructor.
MODULE-2:
2.5 Java Do While Loop
Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while
check for the condition after executing the statements of the loop body.
Syntax :
do
{
// Loop Body
Update_expression
}
// Condition check
while (test_expression );
Note: The test_expression for the do -while loop must return a boolean
n value ,
else we would get a compile-time error.
Java while loop is a control flow statement used to execute the block of
statements repeatedly until the given condition evaluates to false. Once the
condition becomes false, the line immediately after the loop in the program is
executed.
Example Explained
• myMethod() is the name of the method
• static means that the method belongs to the Main class and not an object of the
Main class. You will learn more about objects and how to access methods
through objects later in this tutorial.
• void means that this method does not have a return value. You will learn more
about return values later in this chapter
• Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is
called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
static void myMethod(String fname, int age) {
[Link](fname + " is " + age);
}
// Liam is 5
// Jenny is 8
// Anja is 31
Note that when you are working with multiple parameters, the method call must have
the same number of arguments as there are parameters, and the arguments must be
passed in the same order.
Example:
import [Link];
Benefits:
Method overloading allows multiple methods in the same class to have the same name
but different parameters (either in number, type, or both).
Example:
class OverloadExample {
// Method with two int parameters
int add(int a, int b) {
return a + b;
}
Key Points:
Variable scope determines where a variable can be accessed in a program. Java has
different types of variable scope:
1. Local Scope
2. Instance Scope
class Person {
String name; // Instance variable (different for each object)
void setName(String n) {
name = n;
}
void showName() {
[Link](name);
}
}
class Counter {
static int count = 0; // Static variable (shared across all objects)
Counter() {
count++;
}
void showCount() {
[Link]("Count: " + count);
}
}
4. Block Scope
Summary Table
Method Abstraction
• Method abstraction means hiding the implementation details and exposing only
the functionality.
• In Java, this is achieved using methods: the caller only needs to know the
method signature (name, parameters, return type) and not how it works
internally.
• This improves code readability, reusability, and maintainability.
class Calculator {
// Abstracting the logic inside a method
public int add(int a, int b) {
return a + b;
}
}
Stepwise Refinement
Let's say we want to calculate the area of a rectangle, but we refine it into smaller steps:
import [Link];
class Rectangle {
// Step 2: Calculate the area
public int calculateArea(int length, int width) {
return length * width;
}
}
displayResult(area);
}
}
// Declaration
int[] numbers;
// Initialization
numbers = new int[5]; // Array of size 5
// Declaration + Initialization
int[] values = {10, 20, 30, 40, 50}; // Directly assign values
[Link](arr[1]); // Output: 10
Property Description
length Returns the number of elements in the array
Zero-based index Arrays in Java start at index 0
Fixed size Once created, the array size cannot change
3. Copying Arrays in Java
2. Using [Link]()
• Parameters:
1. Source array
2. Start index in the source array
3. Destination array
4. Start index in the destination array
5. Number of elements to copy
3. Using [Link]()
import [Link];
• Shallow copy means that for non-primitive types (objects), only references are
copied, not actual objects.
5. Using [Link]()
import [Link];
Summary Table
class ArrayExample {
// Method that modifies the array
public static void modifyArray(int[] arr) {
for (int i = 0; i < [Link]; i++) {
arr[i] *= 2; // Doubling each element
}
}
Output:
Key Point: Since arrays are passed by reference, changes made in modifyArray()
affect the original array.
• A method can return an array, just like it returns any other data type.
class ArrayReturnExample {
// Method that generates an array of even numbers
public static int[] generateEvenNumbers(int size) {
int[] evens = new int[size];
for (int i = 0; i < size; i++) {
evens[i] = (i + 1) * 2; // Filling with even numbers
}
return evens; // Returning the array
}
Output:
class MatrixOperations {
// Method to multiply a 2D matrix by a scalar and return the result
public static int[][] multiplyMatrix(int[][] matrix, int scalar) {
int rows = [Link];
int cols = matrix[0].length;
int[][] result = new int[rows][cols];
Output:
[2, 4]
[6, 8]
Key Point: Just like 1D arrays, 2D arrays are also passed by reference, and we
can return them from methods.
Summary Table
Searching means finding an element's index in an array. The two common search
techniques are:
class LinearSearchExample {
public static int linearSearch(int[] arr, int key) {
for (int i = 0; i < [Link]; i++) {
if (arr[i] == key) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
Output:
Found at index: 4
import [Link];
class BinarySearchExample {
public static int binarySearch(int[] arr, int key) {
int left = 0, right = [Link] - 1;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
left = mid + 1;
else
right = mid - 1;
}
return -1; // Not found
}
Output:
Found at index: 4
import [Link];
class BubbleSortExample {
public static void bubbleSort(int[] arr) {
int n = [Link];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
import [Link];
Output:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link](matrix[1][2]); // Output: 6
Output:
123
456
789
int[][][] threeDArray = {
{
{1, 2}, {3, 4}
},
{
{5, 6}, {7, 8}
}
};
[Link](threeDArray[1][0][1]); // Output: 6
Output:
12
34
56
78
Summary Table
Recursion in Java
java
CopyEdit
void recursiveMethod() {
if (base_condition) {
return; // Base Case (Stops recursion)
} else {
recursiveMethod(); // Recursive Case
}
}
Factorial Formula:
class FactorialExample {
public static int factorial(int n) {
if (n == 0) { // Base Case
return 1;
}
return n * factorial(n - 1); // Recursive Call
}
public static void main(String[] args) {
int num = 5;
[Link]("Factorial of " + num + " is: " + factorial(num));
}
}
Output:
Fibonacci Formula:
Base Cases:
• F(0)=0F(0) = 0F(0)=0
• F(1)=1F(1) = 1F(1)=1
class FibonacciExample {
public static int fibonacci(int n) {
if (n == 0) return 0; // Base Case 1
if (n == 1) return 1; // Base Case 2
Output:
Fibonacci of 7 is: 13
class SumOfDigitsExample {
public static int sumOfDigits(int n) {
if (n == 0) return 0; // Base Case
return (n % 10) + sumOfDigits(n / 10); // Recursive Call
}
Output:
Sum of digits: 10
Example:
Input: "hello"
Output: "olleh"
class ReverseStringExample {
public static String reverseString(String str) {
if ([Link]()) return str; // Base Case
return reverseString([Link](1)) + [Link](0); // Recursive Call
}
Output:
Reversed: olleh
6. Example 5: Finding GCD (Greatest Common Divisor) Using Recursion
Euclidean Algorithm:
class GCDExample {
public static int gcd(int a, int b) {
if (b == 0) return a; // Base Case
return gcd(b, a % b); // Recursive Call
}
Output:
Problem: Move n disks from Source (A) to Target (C) using Auxiliary (B).
Base Case: If only 1 disk, move it directly.
Recursive Case:
class TowerOfHanoi {
public static void solveHanoi(int n, char source, char auxiliary, char target) {
if (n == 1) {
[Link]("Move disk 1 from " + source + " to " + target);
return;
}
solveHanoi(n - 1, source, target, auxiliary);
[Link]("Move disk " + n + " from " + source + " to " + target);
solveHanoi(n - 1, auxiliary, source, target);
}
public static void main(String[] args) {
int disks = 3;
solveHanoi(disks, 'A', 'B', 'C');
}
}
Output:
8. Summary Table
Fibonacci `n == 0
1. Abstraction in Java
Achieved using:
Abstract classes (abstract keyword)
Interfaces (interface keyword)
java
CopyEdit
abstract class Vehicle {
abstract void start(); // Abstract method (no body)
}
2. Encapsulation in Java
Encapsulation is the process of wrapping data (variables) and methods within a class
and restricting direct access to them. It helps in data hiding and data protection.
Achieved using:
Declaring variables as private
Providing public getter and setter methods
java
CopyEdit
class Person {
private String name; // Private variable
// Getter method
public String getName() {
return name;
}
// Setter method
public void setName(String newName) {
[Link] = newName;
}
}
You can use both concepts together to create robust and secure applications.
java
CopyEdit
abstract class BankAccount {
private double balance; // Encapsulated variable
@Override
void withdraw(double amount) {
if (amount <= getBalance()) {
deposit(-amount);
[Link]("Withdrawal successful. New balance: " + getBalance());
} else {
[Link]("Insufficient balance.");
}
}
}
Output:
sql
CopyEdit
Withdrawal successful. New balance: 500.0
Insufficient balance.
4.2 Thinking in Objects, Processing Primitive Data Type Values as
Objects, Types, The Big Integer, and Big Decimal Classes.
1. Thinking in Objects
java
CopyEdit
class Car {
String brand;
int speed;
void accelerate() {
speed += 10;
[Link](brand + " is now running at " + speed + " km/h");
}
}
java
CopyEdit
public class WrapperExample {
public static void main(String[] args) {
Integer num = 10; // Autoboxing (int → Integer)
int primitiveNum = num; // Unboxing (Integer → int)
[Link]("Integer object: " + num);
[Link]("Primitive int: " + primitiveNum);
}
}
Output:
pgsql
CopyEdit
Integer object: 10
Primitive int: 10
3. Types in Java
Since int and long have limited range, BigInteger is used for large integer calculations.
✔ Found in [Link]
✔ Supports arbitrary precision
✔ Provides methods for arithmetic operations, GCD, primality testing, etc.
java
CopyEdit
import [Link];
Output:
makefile
CopyEdit
Sum: 1111111111111111110
Product: 121932631356500531347203169112635269
Since double and float cannot precisely store decimal values, BigDecimal is used for
high-precision decimal calculations.
✔ Found in [Link]
✔ Useful for financial applications (avoids rounding errors)
✔ Supports arithmetic operations, rounding modes, and scale setting
java
CopyEdit
import [Link];
Output:
vbnet
CopyEdit
Sum: 13.39
Division (Rounded to 2 decimals): 3.27
4.3 The String Class, The String Builder and String Buffer Class,
Super-Class and Sub-Classes.
Creating Strings
java
CopyEdit
public class StringExample {
public static void main(String[] args) {
String s1 = "Hello"; // String literal
String s2 = new String("World"); // Using new keyword
[Link](s1 + " " + s2); // Output: Hello World
}
}
Method Description
length() Returns length of string
charAt(index) Returns character at the given index
concat(str) Joins two strings
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
substring(start, end) Extracts a substring
equals(str) Checks if two strings are equal
compareTo(str) Compares two strings lexicographically
trim() Removes leading and trailing spaces
java
CopyEdit
public class StringMethods {
public static void main(String[] args) {
String str = " Java Programming ";
Key Takeaways:
Since String is immutable, modifications create new objects in memory, which can be
inefficient.
To solve this, Java provides mutable alternatives:
StringBuilder Class
java
CopyEdit
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // Modifies the same object
[Link](sb); // Output: Hello World
}
}
StringBuffer Class
A super-class (or base class) is a generalized class that other classes inherit from.
It contains common attributes and methods that can be reused in sub-classes.
A sub-class (or derived class) inherits properties and behaviors from a super-class
using the extends keyword.
java
CopyEdit
// Super-Class (Parent)
class Animal {
String name;
void eat() {
[Link](name + " is eating");
}
}
// Sub-Class (Child)
class Dog extends Animal {
void bark() {
[Link](name + " is barking");
}
}
Output:
csharp
CopyEdit
Buddy is eating
Buddy is barking
Super Keyword
java
CopyEdit
// Super-Class
class Vehicle {
int speed = 50;
void display() {
[Link]("Vehicle is moving at speed: " + speed);
}
}
// Sub-Class
class Car extends Vehicle {
int speed = 100; // Overriding speed variable
void display() {
[Link](); // Calls super-class method
[Link]("Car is moving at speed: " + speed);
}
}
Output:
csharp
CopyEdit
Vehicle is moving at speed: 50
Car is moving at speed: 100
The super keyword in Java is used to refer to the immediate parent class (superclass).
Uses of super
java
CopyEdit
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}
Output:
css
CopyEdit
Animal makes a sound
Dog barks
Example 2: Using super to Access Superclass Fields
java
CopyEdit
class Vehicle {
int speed = 50;
}
void displaySpeed() {
[Link]("Car speed: " + speed);
[Link]("Vehicle speed: " + [Link]); // Accesses the speed
variable from Vehicle
}
}
Output:
yaml
CopyEdit
Car speed: 100
Vehicle speed: 50
java
CopyEdit
class Animal {
Animal() {
[Link]("Animal Constructor");
}
}
Output:
nginx
CopyEdit
Animal Constructor
Dog Constructor
✔ The method must have the same name and same parameters as the parent class
method.
✔ The method must be in a subclass (inheritance is required).
✔ Access level cannot be more restrictive (e.g., if the parent method is public, the
overridden method cannot be private).
✔ The method cannot be overridden if it is static, final, or private.
java
CopyEdit
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}
Output:
nginx
CopyEdit
Cat meows
Where it
Between superclass & subclass Within the same class
occurs
java
CopyEdit
class MathOperations {
// Method Overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
class AdvancedMath extends MathOperations {
// Method Overriding
@Override
int add(int a, int b) { return a + b + 10; }
}
Output:
makefile
CopyEdit
Overloading: 15
Overriding: 25
Every class in Java implicitly extends the Object class, which is the parent of all classes.
Method Description
clone() Creates a copy of the object (if the class implements Cloneable)
java
CopyEdit
class Person {
String name;
Person(String name) {
[Link] = name;
}
}
Output:
less
CopyEdit
Person@15db9742 (Default output: className@hashCode)
java
CopyEdit
class Person {
String name;
int age;
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
public class OverriddenToString {
public static void main(String[] args) {
Person p = new Person("Alice", 25);
[Link](p); // Calls overridden toString()
}
}
Output:
css
CopyEdit
Person[name=Alice, age=25]
1. Polymorphism in Java
Types of Polymorphism
java
CopyEdit
class MathOperations {
int add(int a, int b) {
return a + b;
}
Output:
yaml
CopyEdit
Addition of integers: 15
Addition of doubles: 8.0
Output:
nginx
CopyEdit
Dog barks
✔ Explanation: Even though myPet is of type Animal, the overridden method in Dog is
called due to dynamic method dispatch.
Dynamic binding (late binding) means that method calls are resolved at runtime, not
compile-time.
It is used in method overriding to determine which method to call based on the
actual object type.
java
CopyEdit
class Parent {
void display() {
[Link]("Parent class method");
}
}
class Child extends Parent {
@Override
void display() {
[Link]("Child class method");
}
}
Output:
kotlin
CopyEdit
Child class method
✔ Explanation: The display() method in the Child class is executed due to dynamic
binding.
java
CopyEdit
class Animal {
void makeSound() {
[Link]("Animal sound");
}
}
if (a instanceof Cat) {
Cat c = (Cat) a; // Downcasting (Explicit)
[Link]();
}
}
}
Output:
nginx
CopyEdit
Animal sound
Cat purrs
✔ Explanation:
The equals() method in the Object class compares object references by default.
It should be overridden to compare object data instead of memory addresses.
java
CopyEdit
class Person {
String name;
Person(String name) {
[Link] = name;
}
}
Output:
arduino
CopyEdit
false
java
CopyEdit
class Person {
String name;
Person(String name) {
[Link] = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != [Link]()) return false;
Person person = (Person) obj;
return [Link]([Link]);
}
}
Output:
arduino
CopyEdit
true
✔ Explanation:
• equals() now compares names, not memory addresses.
java
CopyEdit
import [Link];
// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
// Accessing elements
[Link]("First fruit: " + [Link](0));
// Modifying elements
[Link](1, "Blueberry");
// Removing an element
[Link]("Cherry");
// Checking size
[Link]("Size of ArrayList: " + [Link]());
}
}
Output:
yaml
CopyEdit
First fruit: Apple
Fruits:
Apple
Blueberry
Size of ArrayList: 2
5.1 Exception-Handling Overview, Exception Types, the Finally
Clause, Defining Custom Exception Classes
An exception is an event that disrupts the normal flow of a program. Java provides a
structured way to handle exceptions to prevent crashes and ensure stability.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// Optional block, always executes
}
2. Exception Types
import [Link].*;
C) Errors
Output:
Java allows you to create custom exceptions by extending the Exception class.
Output:
An abstract class is a class that cannot be instantiated and may contain abstract
methods (methods without a body). It serves as a base class for other classes.
// Concrete method
void sleep() {
[Link](name + " is sleeping.");
}
}
@Override
void makeSound() {
[Link](name + " barks!");
}
}
2. Interfaces in Java
An interface in Java defines a contract that a class must follow but does not contain any
concrete implementations.
Example of an Interface
interface Vehicle {
void start();
}
The Comparable interface is used for sorting objects in Java. It allows a class to define
a natural ordering by implementing the compareTo method.
Key Features
Single-method interface: int compareTo(T obj).
Used for sorting objects in collections (TreeSet, TreeMap, [Link](), etc.).
Returns:
import [Link].*;
@Override
public String toString() {
return name + " (" + age + ")";
}
}
✔ Use an abstract class when: You want to share code among related classes.
✔ Use an interface when: You want multiple classes to follow a common contract.
Java provides multiple ways to handle text input/output, including File Handling.
import [Link].*;
import [Link].*;
Java provides two main ways to handle file input and output: Text I/O and Binary I/O.
Feature Text I/O Binary I/O
Data Type Reads/writes text (characters) Reads/writes raw bytes
Uses character encoding (e.g.,
Encoding No encoding, stores raw binary data
UTF-8)
Slower (encoding/decoding
Speed Faster (direct byte storage)
overhead)
Usage For text files (e.g., .txt, .csv) For binary files (e.g., .jpg, .mp3, .exe)
Java BufferedReader, BufferedWriter, FileInputStream, FileOutputStream,
Classes FileReader, FileWriter ObjectInputStream, ObjectOutputStream
import [Link].*;
T getValue() {
return value;
}
}
4. Generic Interfaces
A generic interface defines a contract that multiple classes can follow.
Example of a Generic Interface
// Generic interface
interface Computable<T> {
T compute(T a, T b);
}
A generic method is a method that uses type parameters to allow flexible and reusable
code. These methods enable type safety and can work with multiple data types without
explicit casting.
import [Link];
What is a Thread?
A thread is a lightweight process that shares memory with other threads of the same
process.
🛠 Java supports multithreading using the Thread class and Runnable interface.
PrintNumbers(String name) {
[Link] = name;
}
[Link]();
[Link]();
}
}
Output (Order may vary due to concurrency):
Thread-1: 1
Thread-2: 1
Thread-1: 2
Thread-2: 2
Thread-1: 3
Thread-2: 3
3. Thread Synchronization
When multiple threads share resources, data inconsistency can occur. Synchronization
helps avoid this.
// Synchronized method
public synchronized void increment() {
count++;
}
[Link]();
[Link]();
[Link]();
[Link]();
We create a thread by extending the Thread class and overriding the run() method.
Example:
Thread running: 1
Thread running: 2
Thread running: 3
Thread running: 4
Thread running: 5
Key Points:
The Runnable interface is preferred because it allows multiple threads to share the
same object.
Example:
Output:
Runnable Thread: 1
Runnable Thread: 2
Runnable Thread: 3
Runnable Thread: 4
Runnable Thread: 5
Advantages of Runnable:
Example:
MyTask(String name) {
[Link] = name;
}
[Link]();
[Link]();
}
}
Thread-1 - Count: 1
Thread-2 - Count: 1
Thread-1 - Count: 2
Thread-2 - Count: 2
Thread-1 - Count: 3
Thread-2 - Count: 3
Key Points:
• Multiple threads execute simultaneously.
• Execution order is unpredictable (depends on CPU scheduling).
State Description
NEW Thread is created but not started (new Thread()).
RUNNABLE Thread is started and ready to run.
RUNNING Thread is currently executing (run() method).
BLOCKED Thread is waiting for a resource (e.g., lock).
WAITING Thread is waiting indefinitely for another thread’s signal.
TIMED_WAITING Thread is waiting for a specific amount of time ([Link]()).
TERMINATED Thread has finished execution.
The join() method ensures that the main thread waits for another thread to finish before
continuing.
Example:
Worker(String name) {
[Link] = name;
}
Worker-1 is working... 1
Worker-1 is working... 2
Worker-1 is working... 3
Worker-2 is working... 1
Worker-2 is working... 2
Worker-2 is working... 3
Key Points:
6. Thread Priorities
• Thread.MIN_PRIORITY = 1
• Thread.NORM_PRIORITY = 5 (Default)
• Thread.MAX_PRIORITY = 10
Example:
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}
Key Point: Priority does not guarantee execution order (depends on OS scheduling).
7. Daemon Threads