Module 1 Part1
Module 1 Part1
Introduction - Java features – Java Platform – Java Fundamentals – Expressions, Operators, and
Control Structures–Constructor-The Java Class- Inheritance, Derived Classes, Method Overriding,
Method Overloading, Abstract Class and Method, Interfaces, Packages.
What is Java?
• Java is a high level programming language and it is also called as a platform. Java is a secured
and robust high level object-oriented programming language.
• Platform: Any software or hardware environment in which a program runs is known as a
platform.
• Java has its own runtime environment (JRE) and API so java is also called as platform.
• Java follows the concept of Write Once, Run Anywhere.
Applications of Java
1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games
8. Robotics etc.
History of Java
Java history begins from Green Team. The Java team members (otherwise called Green Team), started a
revolutionary task to build up a language for digital devices, for example, set-top boxes, televisions and
so on. For the green team members, it was the advanced concept at that time. However, it was suitable for
internet programming. Afterwards, Java technology as joined by Netscape. At present, Java is used in
many places such as internet programming, mobile devices, games, e-business solutions and so on. There
are given the main points which describe the history of java.
o James Gosling, Mike Sheridan, and Patrick Naughton started the Java language project in
June 1991. The tiny team of sun engineers called Green Team.
o In the beginning, it is designed for small, embedded systems in electronic appliances like
set-top boxes.
oFirst of all, it was known as "Greentalk" by James Gosling and .gt was the file extension.
oLater, it was known as Oak and was developed as a piece of the Green project.
Why "Oak" name
• Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A., France,
Germany, Romania etc.
• In the year 1995, Oak was renamed as "Java" since it was previously a trademark by Oak
Technologies.
Why "Java" name
• The team gathered to decide a new name. The recommended words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA" and so on.
• They needed something that mirrored the quintessence of the technology: revolutionary,
dynamic, cool, unique, and simple to spell and fun to say.
• As indicated by James Gosling, "Java was one of the best choices along with Silk".
• Since java was so unique, majority of the team members favored java.
• The Java is an island of Indonesia where first coffee was produced (known as java coffee).
• Notice that Java is only a name not an acronym.
• Initially developed by James Gosling at Sun Microsystems (which is currently a subsidiary of
Oracle Corporation) and then released in 1995.
• In the year 1995, Time magazine said Java is one of the Ten Best Products of 1995.
• JDK 1.0 released in (23rd January, 1996).
Java Version History
• There are numerous java versions are released. Present stable release of Java will be Java SE 8.
o JDK Alpha and Beta (1995)
o JDK 1.0 (23rd Jan, 1996)
o JDK 1.1 (19th Feb, 1997)
o J2SE 1.2 (8th Dec, 1998)
o J2SE 1.3 (8th May, 2000)
o J2SE 1.4 (6th Feb, 2002)
o J2SE 5.0 (30th Sep, 2004)
o Java SE 6 (11th Dec, 2006)
o Java SE 7 (28th July, 2011)
o Java SE 8 (18th March, 2014)
o Java SE 9 (21th Sep, 2017)
Special Features of Java
o Simple
o Object-Oriented
o Portable
o Platform independent
o Secured
o Robust
o Architecture neutral
o Dynamic
o Interpreted
o High Performance
o Multithreaded
o Distributed
o
Simple
Platform Independent
• A platform is the hardware or software environment in which a program runs. There are two types
of platforms one is software-based another one is hardware-based. The Java platform differs from
most other platforms in the sense that it is a software-based platform that runs on the top of other
hardware-based platforms. It has two components:
o Runtime Environment
o API(Application Programming Interface)
• The Java code can be running on multiple platforms like Windows, Linux, Sun Solaris, and
Mac/OS and so on.
• This code is compiled by the compiler and then converted it into a bytecode.
• This bytecode is platform-independent code since it can be running on multiple platforms i.e.
Write Once and Run Anywhere (WORA).
Secured
• Robust simply means strong. Java uses strong memory management. There is lack of pointers that
avoids security problem.
• There is automatic garbage collection in java.
• In Java exception handling and type checking mechanism are available. These all make java
robust.
Architecture-neutral
• There are no implementation dependent features (e.g. size of primitive types is fixed).
• In C programming, int data type occupies two bytes of memory for 32-bit architecture and four
bytes of memory for 64-bit architecture. However in java, it occupies four bytes of memory for
both 32 and 64 bit architectures.
Portable
• The Java programming language is quicker than traditional interpretation whereas the byte code
is "close" to local code still slower than compiled language like C++.
Distributed
• You can make distributed applications in java. The RMI and EJB are used for making distributed
applications.
• We might access files by calling the methods from several machine on the internet/web.
Multi-threaded
• Thread is similar to a separate program, it executing concurrently. You can write Java codes that
deal with lots of tasks at only once by defining multiple threads.
• The most important benefit of multi-threading is, it couldn’t occupies memory for each thread and
it shares a common memory area to every thread. Threads are important for multi-media, Web
applications and so on.
Key words
• In Java, keywords are reserved words that have a predefined meaning in the language.
• They form the foundation of Java's syntax and cannot be used as identifiers, such as variable
names, method names, or class names.
• Each keyword has a specific function, and the Java compiler uses these to parse the structure of
Java code.
Keyword Description
static Declares a static member that belongs to the class, not instances.
1. Open a Text Editor: You can use any text editor, such as Notepad, TextEdit, or an Integrated Development
Environment (IDE) like Eclipse or IntelliJ IDEA.
2. Write the Code: Type the following code into your text editor:
System.out.println("Hello, World!");
• public class HelloWorld: This line declares a public class named HelloWorld. In Java, every application must
have at least one class definition.
• public static void main(String[] args): This is the main method, the entry point for any Java application.
The main method is always required in a standalone Java application.
• System.out.println("Hello, World!");: This line prints the text "Hello, World!" to the console. System.out is a
standard output stream, and println is a method that prints a line of text.
1. Save the File: Save your file with the name HelloWorld.java. The filename must match the class name and be
case-sensitive.
2. Open Command Prompt/Terminal: Navigate to the directory where your HelloWorld.java file is saved.
3. Compile the Program: Enter the following command to compile your program:
javac HelloWorld.java
This command uses the Java compiler (javac) to convert your Java code into bytecode, generating
a HelloWorld.class file.
After successful compilation, run your program with the following command:
java HelloWorld
Hello, World!
• Case Sensitivity: Java is case-sensitive. Ensure that you use the correct capitalization for class names, method
names, and file names.
• File Naming: The filename must match the public class name exactly, including capitalization.
• Environment Setup: Ensure that Java Development Kit (JDK) is installed and configured correctly on your
system. You can verify the installation by running java -version and javac -version in your command prompt or
terminal.
• Use Comments: Add comments to your code to improve readability and maintainability. For example:
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution
when testing alternative code.
1.Single-line Comments
Any text between // and the end of the line is ignored by Java (will not be executed).
// This is a comment
System.out.println("Hello World");
Example
This example uses a multi-line comment (a comment block) to explain the code:
Example
System.out.println("Hello World");
Java Data Types
Java programming language has a rich set of data types. The data type is a category of data stored in variables.
In java, data types are classified into two types and they are as follows.
The primitive data types are built-in data types and they specify the type of value stored in a variable and the
memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.
The following table provides more description of each primitive data type.
In java, non-primitive data types are the reference data types or user-created data types. All non-primitive data
types are implemented using object concepts. Every variable of the non-primitive data type is an object. The non-
primitive data types may use additional methods to perform certain operations. The default value of non- primitive
data type variable is null.
In java, examples of non-primitive data types are String, Array, List, Queue, Stack, Class, Interface, etc.
Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a container that
holds a data value.
In java, we use the following syntax to create variables.
Syntax
data_type
variable_name; (or)
data_type variable_name_1,
variable_name_2,...; (or)
• Local variables
• Instance variables or Member variables or Global variables
• Static variables or Class variables
• Final variables
Local variables
The variables declared inside a method or a block are known as local variables. A local variable is visible within
the method in which it is declared. The local variable is created when execution control enters into the method or
block and destroyed after the method or block execution completed.
Let's look at the following example java program to illustrate local variable in java.
int b = 20;
obj.display();
}
}
The variables declared inside a class and outside any method, constructor or block are known as instance variables
or member variables. These variables are visible to all the methods of the class. The changes made to these
variables by method affects all the methods in the class. These variables are created separate copy for every object
of that class.
Let's look at the following example java program to illustrate instance variable in java.
Example
= 100;
obj.display();
A static variable is a variable that declared using static keyword. The instance variables can be static variables
but local variables can not. Static variables are initialized only once, at the start of the program execution. The
static variable only has one copy per class irrespective of how many objects we create.
The static variable is access by using class name.
Let's look at the following example java program to illustrate static variable in java.
Example
A final variable is a variable that declared using final keyword. The final variable is initialized only once, and
does not allow any method to change it's value again. The variable created using final keyword acts as constant.
All variables like local, instance, and static variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.
Example
int a = 10;
void show() {
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
int myInt = 9;
System.out.println(myInt); // Outputs 9
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses () in front of the value:
Example
System.out.println(myInt); // Outputs 9
Java Arrays
• An array is a collection of similar data values with a single name.
• An array can also be defined as, a special type of variable that holds multiple values of the same data
type at a time.
• In java, arrays are objects and they are created dynamically using new operator.
• Every array in java is organized using index values.
• The index value of an array starts with '0' and ends with 'size-1'.
• We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
• One Dimensional Array
• Multi-Dimensional Array
Creating an array
In the java programming language, an array must be created using new operator and with a specific size. The
size must be an integer value but not a byte, short, or long. We use the following syntax to create an array.
Syntax
list[0] = 10;
In java, an array can also be initialized at the time of its declaration. When an array is initialized at the time of
its declaration, it need not specify the size of the array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich set of operators.
In java, operators are classified into the following four types.
• Arithmetic Operators
• Relational (or) Comparison Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Conditional Operators
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
++ Increment a++
-- Decrement a--
◻ The addition operator can be used with numerical data types and character or string data type. When it is used
with numerical values, it performs mathematical addition and when it is used with character or string data type
values, it performs concatenation (appending).
◻ The modulus (remainder of the division) operator is used with integer data type only.
◻ The increment and decrement operators are used as pre-increment or pre-decrement and post-
increment or post-decrement.
◻ When they are used as pre, the value is get modified before it is used in the actual expresion and when it is
used as post, the value is get modified after the the actual expression evaluation.
The relational operators are the symbols that are used to compare two values. That means the relational operators
are used to check the relationship between two values. Every relational operator has two posible results either
TRUE or FALSE. In simple words, the relational operators are used to define conditions in a program. The
following table provides information about relational operators.
>= Returns TRUE if the first value is larger than or equal to 10 >= 5 is TRUE
second value otherwise returns FALSE
!= Returns TRUE if both values are not equal otherwise returns 10 != 5 is TRUE
FALSE
Look at the following example program.
Example
a = 10<5;
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one condition. The
following table provides information about logical operators.
& Logical AND - Returns TRUE if all conditions are TRUE otherwise false & true =>
returns FALSE false
| Logical OR - Returns FALSE if all conditions are FALSE otherwise false | true => true
returns TRUE
^ Logical XOR - Returns FALSE if all conditions are same otherwise true ^ true => false
returns TRUE
! Logical NOT - Returns TRUE if condition is FLASE and returns !false => true
FALSE if it is TRUE
&& short-circuit AND - Similar to Logical AND (&), but once a false & true =>
decision is finalized it does not evaluate remianing. false
|| short-circuit OR - Similar to Logical OR (|), but once a decision is false | true => true
finalized it does not evaluate remianing.
◻ The operators &, |, and ^ can be used with both boolean and integer data type values. When they are used
with integers, performs bitwise operations and with boolean, performs logical operations.
◻ Logical operators and Short-circuit operators both are similar, but in case of short-circuit operators once the
decision is finalized it does not evaluate remaining expressions.
Example
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable (Lvalue).
The assignment operator is used in different variants along with arithmetic operators. The following table
describes all the assignment operators in the java programming language.
+= Add both left and right-hand side values and store the result into left- A += 10
hand side variable
-= Subtract right-hand side value from left-hand side variable value and A -= B
store the result into left-hand side variable
*= Multiply right-hand side value with left-hand side variable value and A *= B
store the result into left-hand side variable
/= Divide left-hand side variable value with right-hand side variable value A /= B
and store the result into the left-hand side variable
%= Divide left-hand side variable value with right-hand side variable value A %= B
and store the remainder into the left-hand side variable
|= Logical OR assignment -
boolean x = true;
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values.
The following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16
(10000)
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)
<< the Bitwise left shift operator shifts all the bits to the left by the specified A << 2
number of positions ⇒ 100 (1100100)
>> the Bitwise right shift operator shifts all the bits to the right by the specified A >> 2
number of positions ⇒ 6 (00110)
Conditional Operators
The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first, we verify a condition, then we perform one operation
out of the two operations based on the condition result. If the condition is TRUE the first option is performed, if
the condition is FALSE the second option is performed. The conditional operator is used with the following
syntax.
Syntax
Example
c = (a>b)? a : b;
System.out.println("c = " + c);
Java Expressions
• In any programming language, if we want to perform any calculation or to frame any condition etc., we
use a set of symbols to perform the task.
• In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.
• Operands are the values on which the operators perform the task. Here operand can be a direct value or
variable or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
• Infix Expression
• Postfix Expression
• Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
In java, the default execution flow of a program is a sequential order. But the sequential order of execution flow
may not be suitable for all situations. Sometimes, we may want to jump from line to another line, we may want
to skip a part of the program, or sometimes we may want to execute a part of the program again and again. To
solve this problem, java provides control statements.
In java, the control statements are the statements which will tell us that in which order the instructions are getting
executed. The control statements are used to control the order of execution according to our requirements. Java
provides several control statements, and they are classified as follows.
In java, the selection statements are also known as decision making statements or branching statements. The
selection statements are used to select a part of the program to be executed based on a condition. Java provides
the following selection statements.
• if statement
• if-else statement
• if-elif statement
• nested if statement
• switch statement
In java, the iterative statements are also known as looping statements or repetitive statements. The iterative
statements are used to execute a part of the program repeatedly as long as the given condition is True. Using
iterative statements reduces the size of the code, reduces the code complexity, makes it more efficient, and
increases the execution speed. Java provides the following iterative statements.
• while statement
• do-while statement
• for statement
• for-each statement
Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the next iteration. Java
provides the following jump statements.
• break
• continue
• return
In java, the selection statements are also known as decision making statements or branching statements or
conditional control statements. The selection statements are used to select a part of the program to be executed
based on a condition. Java provides the following selection statements.
• if statement
• if-else statement
• nested if statement
• if-else if statement
• switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements based on that
condition result. The if statement checks, the given condition then decides the execution of a block of statements.
If the condition is True, then the block of statements is executed and if it is False, then the block of statements is
ignored. The syntax and execution flow of if the statement is as follows.
Let's look at the following example java code.
Java Program
import java.util.Scanner;
public class IfStatementTest {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = read.nextInt();
if((num % 5) == 0) {
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the condition
is evaluated to False. Then the if statement ignores the execution of its block of statements.
When we enter a number which is divisible by 5, then it produces the output as follows.
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a block of statements out of two
blocks based on that condition result. The if-else statement checks the given condition then decides which block
of statements to be executed based on the condition result. If the condition is True, then the true block of
statements is executed and if it is False, then the false block of statements is executed. The syntax and execution
flow of if-else statement is as follows.
import java.util.Scanner;
public class IfElseStatementTest {
public static void main(String[] args) {
else {
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}
System.out.println("We are outside the if-block!!!");
}
Writing an if statement inside another if-statement is called nested if statement. The general syntax of the nested
if-statement is as follows.
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
...
import java.util.Scanner;
public class NestedIfStatementTest {
public static void main(String[] args) {
}
if-else if statement in java
Writing an if-statement inside else of an if statement is called if-else-if statement. The general syntax of the an
if-else-if statement is as follows.
Syntax
if(condition_1){
condition_1 true-block;
...
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
Java Program
import java.util.Scanner;
public class IfElseIfStatementTest {
public static void main(String[] args) {
int num1, num2, num3;
Scanner read = new Scanner(System.in);
System.out.print("Enter any three numbers: ");
num1 = read.nextInt();
num2 = read.nextInt();
num3 = read.nextInt();
if( num1>=num2 && num1>=num3)
System.out.println("\nThe largest number is " + num1) ;
else if (num2>=num1 && num2>=num3)
System.out.println("\nThe largest number is " + num2) ;
else
System.out.println("\nThe largest number is " + num3) ;
System.out.println("\nWe are outside the if-block!!!");
}
Using the switch statement, one can select only one option from more number of options very easily. In the switch
statement, we provide a value that is to be compared with a value associated with each option. Whenever the
given value matches the value associated with an option, the execution starts from that option. In the switch
statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
Let's look at the following example java code.
Java Program
import java.util.Scanner;
public class SwitchStatementTest {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Press any digit: ");
int value = read.nextInt();
switch( value )
{
The java programming language provides a set of iterative statements that are used to execute a statement or a
block of statements repeatedly as long as the given condition is true. The iterative statements are also known as
looping statements or repetitive statements. Java provides the following iterative statements.
• while statement
• do-while statement
• for statement
• for-each statement
while statement in java
The while statement is used to execute a single statement or block of statements repeatedly as long as the given
condition is TRUE. The while statement is also known as Entry control looping statement. The syntax and
execution flow of while statement is as follows.
Java Program
The do-while statement is used to execute a single statement or block of statements repeatedly as long as given
the condition is TRUE. The do-while statement is also known as the Exit control looping statement. The do-
while statement has the following syntax.
Let's look at the following example java code.
Java Program
❖ The for statement is used to execute a single statement or a block of statements repeatedly as long as the
given condition TRUE.
❖ In for-statement, the execution begins with the initialization statement.
❖ After the initialization statement, it executes Condition.
❖ If the condition is evaluated to true, then the block of statements executed otherwise it terminates the
for-statement.
❖ After the block of statements execution, the modification statement gets executed, followed by
condition again.
is T
The Java for-each statement was introduced since Java 5.0 version. It provides an approach to traverse through
an array or collection in Java. The for-each statement also known as enhanced for statement. The for-each
statement executes the block of statements for each element of the given array or collection.
◻ In for-each statement, we can not skip any element of given array or collection.
The for-each statement has the following syntax and execution flow diagram.
}
Java Jump Statements
The java programming language supports jump statements that used to transfer execution control from one line
to another line. The java programming language provides the following jump statements.
• break statement
• continue statement
The break statement in java is used to terminate a switch or looping statement. That means the break statement
is used to come out of a switch statement and a looping statement like while, do-while, for, and for-each.
◻ Using the break statement outside the switch or loop statement is not allowed.
The following picture depicts the execution flow of the break statement.
if(i == 30)
break;
System.out.println(i);
}
The continue statement is used to move the execution control to the beginning of the looping statement. When
the continue statement is encountered in a looping statement, the execution control skips the rest of the statements
in the looping block and directly jumps to the beginning of the loop. The continue statement can be used with
When we use continue statement with while and do-while statements, the execution control directly jumps to the
condition. When we use continue statement with for statement the execution control directly jumps to the
modification portion (increment/decrement/any modification) of the for loop. The continue statement flow of
execution is as shown in the following figure.
The java programming langauge does not support goto statement, alternatively, the break and continue
statements can be used with label.
The labelled break statement terminates the block with specified label. The labbeled contonue statement takes
the execution control to the beginning of a loop with specified label.
import java.util.Scanner;
public class JavaLabelledStatement {
public static void main(String args[]) {
Scanner read = new Scanner(System.in);
reading: for (int i = 1; i <= 3; i++) {
System.out.print("Enter a even number: ");
int value = read.nextInt();
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more options...");
continue reading;
}
}
return statement in java
In java, the return statement used to terminate a method with or without a value. The return statement takes the
execution control to the calling function. That means the return statement transfer the execution control from
called function to the calling function by carrying a value.
◻ Java allows the use of return-statement with both, with and without return type methods.
In java, the return statement used with both methods with and without return type. In the case of a method with
the return type, the return statement is mandatory, and it is optional for a method without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is used without a
return type, it does not carry any value. Instead, simply transfers the execution control.
import java.util.Scanner;
public class JavaReturnStatementExample {
int value; int readValue() {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
return this.value=read.nextInt(); }
void showValue(int value) {
for(int i = 0; i <= value; i++) {
if(i == 5) return;
System.out.println(i);
} }
public static void main(String[] args) {
} }