Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Java Basics

The document discusses the history and features of the Java programming language. It covers topics like the origins and development of Java, differences between Java and other languages like C and C++, Java versions and applications, and key Java concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java Basics

The document discusses the history and features of the Java programming language. It covers topics like the origins and development of Java, differences between Java and other languages like C and C++, Java versions and applications, and key Java concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 130

OOPs with JAVA-21ISE46A

Module-I

1
Introduction to Java: The Java Language
• Java Programming is a general-purpose object-oriented
programming language, designed for the development of
software for consumer electronic devices such as TVs, VCRs,
toasters, etc.
• Java is a class-based, object-oriented programming language
and is designed to have as few implementation dependencies
as possible.
• Java is a platform neutral language, which means it is not tied
to any particular hardware or operating system. It guarantees
users to ‘write once, run anywhere’.

2
• Java language is supported by almost every operating
system such as Sun Solaris, RedHat, Windows etc.

• Java applications are compiled to byte code that can run


on any Java Virtual Machine.

• The syntax of Java is similar to c/c++.

• JAVA was developed by Sun Microsystems Inc in the


year 1991, later acquired by Oracle Corporation. It was
developed by James Gosling and Patrick Naughton.

• It helps to create reusable code and modular programs. 3


History of Java
• There is a chronicle of events that occurred during the whole
course of development of the Java language.
• 1990-A team of Sun Microsystems programmers decided to
develop a special software to manipulate consumer
electronic devices. The team headed by James Gosling
• 1991-The team studied various languages present at that
time, viz., C and C++ and announced the new language to be
“Oak”.
• 1992-The team at Sun known as Green Project demonstrated
the application of their new language. For example, to control
a list of home appliances using a hand device with the tiny
touch screen.

4
• 1993-The World Wide Web came to the internet and
transformed the text-based Internet into the graphical rich
environment. The Green Project team came up with an idea
of developing Web applets (tiny programs) that could run on
all types of computers connected to the internet.
• 1994-The team developed a web browser called “HotJava” to
locate and run applet programs on the internet. This made it
immensely popular amongst the internet users.
• 1995-Oak was renamed as “Java”, due to some legal snags.
Java is a name, no acronym.
• 1996-Java programming was established as the leader for
internet programming and also as a general-purpose object-
oriented programming language. Sun releases Java
Development Kit 1.0.
5
• 1997-Sun releases Java Development Kit 1.1 (JDK 1.1)
• 1998-Sun releases the Java 2 with version 1.2 of the Software
Development Kit (SD K 1.2)
• 1999-Sun releases Java 2 platform, Standard Edition (J2SE) and
Enterprise Edition (J2EE)
• 2000-Release ofJ2SE with SDK 1.3.
• 2002-The release of J2SE with SDK 1.4.
• 2004-The release of J2SE with JDK 5.0 (instead of JDK 1.5),
known as J2SE 5.0.
• 2006- The release of Java SE 6.
• 2011- The release of Java SE 7.
• 2014- The release of Java SE 8.
• 2017- The release of Java SE 9.etc
6
• 2023 – Java SE 20
Java programming language is named JAVA. Why?

• After the name OAK, the team decided to give a new


name to it and the suggested words were Silk, Jolt,
revolutionary, DNA, dynamic, etc.
• These all names were easy to spell and fun to say, but they
all wanted the name to reflect the essence of technology.
• In accordance with James Gosling, Java the among the top
names along with Silk, and since java was a unique name
so most of them preferred it.
• Java is the name of an island in Indonesia where the first
coffee(named java coffee) was produced and this name
was chosen by James Gosling while having coffee near
his office.
• Note that Java is just a name, not an acronym. 7
Why Use Java?
• Java works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc.)
• It is one of the most popular programming language in the
world
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support (tens of millions of
developers)
• Java is an object oriented language which gives a clear
structure to programs and allows code to be reused, lowering
development costs
• As Java is close to C++ and C#, it makes it easy for
programmers to switch to Java or vice versa
8
C vs Java vs C++

9
C vs Java
• The major difference between C vs Java Programming language is
that Java is an Object Oriented language and has a mechanism to
define classes and objects.

• The features of C which are not included in Java are:


1) No unique statement keywords of C such as size and typedef.
2) No data types such as struct and union.
3) Java does not define the type modifier keywords such as
auto, extern, register, signed and unsigned.
4) No support for pointer type.
5) Non-availability of preprocessor

• Java requires that the function with no argument must be declared


with empty parenthesis and with the void keyword.
10
Java vs C++
• The main difference between c++ vs Java is that Java is a true
Object-oriented language while C++ just adds an object-
oriented extension to C. The increment operator in C++
indicates the same thing.
• The features listed below are intentionally omitted from Java
language to make it better.
• No support for operator overloading.
• No template classes as in C++.
• A new feature called “interface” in Java programming and
thus not supporting multiple inheritances.
• Java language does not support global variables.
• Java uses a finalize () function instead of the destructor
function.
• There are no header files in Java programming. 11
Where Java is used?
There are many devices where java is currently used. Some of
them are as follows:
• Desktop Applications
• Web Applications
• Mobile
• Embedded System
• Robotics
• Games etc.

12
Types of Java Applications

• Application programs: Application programs are


stand-alone programs that are written to carry
out certain tasks on local computer such as
solving equations, reading and writing files etc.
• Applet Programs: Applets are small Java
programs developed for Internet applications. An
applet located in distant computer can be
downloaded via Internet and executed on a local
computer using Java capable browser.

13
VERSIONS
Major release versions of Java, along with their release
dates:
• JDK 1.0 (January 21, 1996)
• JDK 1.1 (February 19, 1997)
• J2SE 1.2 (December 8, 1998)
• J2SE 1.3 (May 8, 2000)
• J2SE 1.4 (February 6, 2002)
• J2SE 5.0 (September 30, 2004)
• Java SE 6 (December 11, 2006)
• Java SE 7 (July 28, 2011)
• Java SE 8 (March 18, 2014)
14
Latest version

The latest version is JDK 20, which was released


in March 2023.

15
Java Development Kit (JDK)
• The Java Development Kit (JDK) is a software development
environment that offers a collection of tools and libraries
necessary for developing Java applications.
• You need the JDK to convert your source code into a format
that the Java Runtime Environment (JRE) expects.
• The JDK includes the Java Runtime Environment (JRE), an
interpreter (java), a compiler (javac), an archiver (jar), a
documentation generator (javadoc), and some other
development tools.
• The Java Runtime Environment itself consists of the Java
Virtual Machine (JVM), supporting files, and core classes.
• Typically, if you are only interested in running Java programs
on your machine or browser, you only need to install JRE.
However, if you would like to develop an application and do16
• JDK is an implementation of any one of the below given Java
Platforms released by Oracle corporation:
1. Standard Edition Java Platform
2. Enterprise Edition Java Platform
3. Micro Edition Java Platform
• Developers new to Java often confuse the Java Development
Kit and the Java Runtime Environment. The distinction is that
the JDK is a package of tools for developing Java-based
software, whereas the JRE is a package of tools
for running Java code.
• The JRE can be used as a standalone component to simply
run Java programs, but it's also part of the JDK. The JDK
requires a JRE because running Java programs is part of
developing them.
17
Figure shows how the JDK fits into the
Java application development lifecycle.

18
Java Buzzwords
• Java is the most popular object-oriented programming
language. Java has many advanced features, a list of key
features is known as Java Buzz Words.
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Architecture-neutral (or) Platform Independent
• Multi-threaded
• Interpreted
• High performance
• Distributed
19

Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++. In a java programming language, many
complicated features like pointers, operator overloading, structures, unions, etc. have
been removed. One of the most useful features is the garbage collector it makes java
more simple.
Secure
Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a web
application. The applet in java does not allow access to other parts of the computer,
which keeps away from harmful programs like viruses and unauthorized access.

Portable
Portability is one of the core features of java which enables the java programs to run
on any computer or operating system. For example, an applet developed using java
runs on a wide variety of CPUs, operating systems, and browsers connected to the
Internet.

20
Object-oriented
Java is said to be a pure object-oriented programming language. In java,
everything is an object. It supports all the features of the object-oriented
programming paradigm.

Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism
(garbage collector), java is a strictly typed language, it has a strong set of
exception handling mechanism, and many more.

Architecture-neutral (or) Platform Independent


Java has invented to archive "write once; run anywhere, any time,
forever". The java provides JVM (Java Virtual Machine) to archive
architectural-neutral or platform-independent. The JVM allows the java
program created using one operating system can be executed on any
other operating system.

21
Multi-threaded
Java supports multi-threading programming, which allows us to write
programs that do multiple operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode. The byte code is
interpreted to any machine code so that it runs on the native machine.

High Performance
Java performance is high because of the use of bytecode.
The bytecode was used so that it was easily translated into native
machine code.
Distributed
Java programming language supports TCP/IP protocols which enable the
java to support the distributed environment of the Internet. Java also
supports Remote Method Invocation (RMI), this feature enables a program
to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically
updated on a running system and it has a dynamic memory allocation and
deallocation (objects and garbage collector). 22
Byte Code
• Java bytecode is the instruction set for the Java Virtual
Machine. It acts similar to an assembler which is an alias
representation of a C++ code.

• As soon as a java program is compiled, java bytecode is


generated. In more apt terms, java bytecode is the machine
code in the form of a .class file.

• With the help of java bytecode we achieve platform


independence in java.

23
Working Principle
• When we write a program in Java, firstly, the compiler compiles
that program and a bytecode is generated for that piece of code.
• When we wish to run this .class file on any other platform, we
can do so.
• After the first compilation, the bytecode generated is now run by
the Java Virtual Machine and not the processor in consideration.
• This essentially means that we only need to have basic java
installation on any platforms that we want to run our code on.
• Resources required to run the bytecode are made available by
theJava Virtual Machine, which calls the processor to allocate
the required resources.
• JVM's are stack-based so they stack implementation to read the
codes.
24
25
Advantage of Java Bytecode
• Platform independence is one of the soul reasons for which
James Gosling started the formation of java and it is this
implementation of bytecode which helps us to achieve this.

• Hence bytecode is a very important component of any java


program.

• The set of instructions for the JVM may differ from system to
system but all can interpret the bytecode.

• A point to keep in mind is that bytecodes are non-runnable


codes and rely on the availability of an interpreter to execute
and thus the JVM comes into play.
26
• Whenever that method is called during the execution of a
program, the bytecode for that method gets invoked.
• Javac not only compiles the program but also generates the
bytecode for the program.
• Thus, we have realized that the bytecode implementation
makes Java a platform-independent language. This helps to
add portability to Java which is lacking in languages like C or
C++.
• Portability ensures that Java can be implemented on a wide
array of platforms like desktops, mobile devices, severs and
many more. Supporting this, Sun Microsystems captioned
JAVA as "write once, read anywhere" or "WORA" in resonance
to the bytecode interpretation.
27
Machine Code
• Machine code is a set of instructions that is directly machine-
understandable and it is processed by the Central Processing
Unit (CPU).

• Machine code is in binary (0’s and 1’s) format which is


completely different from the byte code and source code.

• It is regarded as the most lowest-level representation of the


source code. Machine code is obtained after compilation or
interpretation. It is also called machine language.

28
29
Difference between Byte Code and Machine Code
Byte Code Machine Code

Byte Code consisting of binary, hexadecimal, macro instructions


like (new, add, swap, etc) and it is not directly understandable by Machine code consisting of binary instructions that are directly
the CPU. It is designed for efficient execution by software such as understandable by the CPU.
a virtual machine, intermediate-level

Byte code is considered as the intermediate-level code. Machine Code is considered as the low-level code.

Byte code is a non-runnable code generated after compilation of Machine code is a set of instructions in machine language or in
source code and it relies on an interpreter to get executed. binary format and it is directly executed by CPU.

Byte code is executed by the virtual machine then the Central Machine code is not executed by a virtual machine it is directly
Processing Unit. executed by CPU.

Byte code is less specific towards machine than the machine Machine code is more specific towards machine than the byte
code. code.

It is platform-independent as it is dependent on the virtual It is not platform independent because the object code of one
machine and the system having a virtual machine can be platform can not be run on the same Operating System. Object
executed irrespective of the platform. varies depending upon system architecture and native
instructions associated with the machine. 30
JVM
• JVM, i.e., Java Virtual Machine.
• JVM is the engine that drives the Java code.
• Mostly in other Programming Languages, compiler produce code
for a particular system but Java compiler produce Bytecode for a
Java Virtual Machine.
• When we compile a Java program, then bytecode is generated.
Bytecode is the source code that can be used to run on any
platform.
• Bytecode is an intermediary language between Java source and
the host system.
• It is the medium which compiles Java code to bytecode which gets
interpreted on a different machine and hence it makes it
Platform/Operating system independent.

31
JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM
should have in OS because JVM is platform dependent.
32
Platform Independent
• Java is called platform independent because of Java Virtual
Machine. As different computers with the different
operating system have their JVM, when we submit
a .class file to any operating system, JVM interprets the
bytecode into machine level language.
• JVM is the main component of Java architecture, and it is
the part of the JRE (Java Runtime Environment).
• A program of JVM is written in C Programming Language,
and JVM is Operating System dependent.
• JVM is responsible for allocating the necessary memory
needed by the Java program.
• JVM is responsible for deallocating memory space.
33
JRE and Java environment
• The JRE is one of three interrelated components for developing
and running Java programs. The other two components are as
follows:
• The Java Development Kit, or JDK, is a set of tools for developing
Java applications. Developers choose JDKs by Java version and by
package or edition—Java Enterprise Edition (Java EE), Java
Standard Edition (Java SE), or Java Mobile Edition (Java ME). Every
JDK always includes a compatible JRE, because running a Java
program is part of the process of developing a Java program.
• The Java Virtual Machine, or JVM, executes live Java applications.
Every JRE includes a default JRE, but developers are free to choose
another that meets the specific resource needs of their
applications.
34
• As the runtime environment for Java, the JRE contains the
Java class libraries, the Java class loader, and the Java
Virtual Machine. In this system:
• The class loader is responsible for correctly loading classes
and connecting them with the core Java class libraries.
• The JVM is responsible for ensuring Java applications have
the resources they need to run and perform well in your
device or cloud environment.
• The JRE is mainly a container for those other components,
and is responsible for orchestrating their activities.

35
How the JRE works with the JVM

• A Java Virtual Machine is a running software system


responsible for executing live Java programs. The JRE is
the on-disk system that takes your Java code, combines
it with the necessary libraries, and starts the JVM to
execute it.
• The JRE contains libraries and software that your Java
programs need to run. As an example, the
Java class loader is part of the Java Runtime
Environment. This important piece of software loads
compiled Java code into memory and connects the
code to the appropriate Java class libraries.
36
37
Syntax of a class
class class_name{
data member;
method;
}

38
Example

class Student {
int id;
String name;
}

39
Object in Java
• In real–world, we see many objects round us like automobiles, dogs,
cats and so on. these kinds of objects have a state and a behavior.
• An object is an instance of a class.
• If you compare the software object with a real-world object in java ,
they have very similar characteristics.
• A class provides the blueprints for objects. So basically an object is
created from a class. In Java the new keyword is used to create new
object in java.
• It’s miles a basic unit of object orientated Programming and
represents the real existence entities.
• An average Java program creates many objects, which as you already
know, have interaction by way of invoking strategies.

40
An object includes :
• state : it’s represented by attributes of an object.
It additionally reflects the properties of an object.
• behavior : it’s represented by means of methods of
an object in java. It also reflects the reaction of
an object with other objects.
• identity : It gives a completely unique name to
an object and allows one object to have
interaction with different items.
41
class Student {
int id;
String name;
public static void main(String args[])
{
Student s1 = new Student();
}}

42
Simple Class Program
class Student {

// field or data member or instance variable


int id;
String name;

public static void main(String args[]) {

// creating an object of Student


Student s1 = new Student();

// accessing member through reference variable


System.out.println(s1.id);

System.out.println(s1.name);

} 43
Java Data Type

• Data types represent the different values to be stored


in the variable. Any value store in Variable using Java
Data type.
• Using Java Data Types we can return value to perform
any operation.
• Data type is used for representing the data in main
memory (RAM) of the computer.
• In java, there are two types of data types
1.Primitive Java data types.
2.Non-primitive Java data types.
44
Primitive data types
• byte, short, int and long data types are used for
storing whole numbers.- integer: numerical
• float and double are used for fractional
numbers.- floating point: numerical
• char is used for storing characters(letters).: non-
numerical
• boolean data type is used for variables that holds
either true or false.- non- numerical

45
Example of Primitive DataType:
public class Primitive_Java {

public static void main(String[] args) {

// DataType Declaration

byte b = 100;
short s = 123;
int i = 123543;
long long_Val = 1234567891;
float float_Val = 12.25f;
double double_Val = 12345.234d;
boolean boolean_True = true;
boolean boolean_false = false;
char char_Val = 'Y';
46
// Print Variable Values

System.out.println("byte Value = " + b);


System.out.println("short Value = " + s);
System.out.println("int Value = " + i);
System.out.println("long Value = " + long_Val);
System.out.println("float Value = " + float_Val);
System.out.println("double Value = " + double_Val);
System.out.println("boolean Value = " + boolean_True);
System.out.println("boolean Value = " + boolean_false);
System.out.println("char Value = " + char_Val);
}

}
47
Non-primitive data types

• Non-primitive data types are created by


programmer.
• String, Array are Non-Primitive Datatypes.
• It is also called as ‘Reference Variables’ or
‘Object reference’ because it refers a memory
location where data is stored.
• On the other hand, primitive data types stores
value.

48
STRING
• It is class in java provided with several methods used to
store group of characters.
• Example: abcd, india123 etc. String is not a primitive data
type because it has methods and only class can have
methods.
• Primitive data types cannot have methods. So, String is a
class which is non-primitive type.
• ‘String’ is used to represent string class.
Example:

String s="World";
49
Array
• Array is non-primitive data type because it
refers to the memory location.
• An array is a collection of like-typed
variables which are referred
to by a common name.
• Syntax
dataType[] arrayRefVar;

50
• type var-name[]; OR type[] var-name;
Eg: int intArray[]; or int[] intArray;
Instantiating an Array in Java
• var-name = new type [size];
Eg:int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to
array OR
int[] intArray = new int[20]; // combining both
statements in one
51
Java Variables
• Variable is a name of memory location where the
value is stored to use within class, Method etc…
• Each variable in Java has a specific Datatype to
store Value.
• Which decides the size and layout of the java
variables memory.
• Values can be put away inside that memory, and
the arrangement of activities that can be
connected to the variable.
52
•There are three different kinds of variable in Java
1.Local variables
2.Instance variables
3.Class / Static variables

class Variable_Java {

int instance_Var = 50;// instance variable

static int static_Vat = 100;// static variable

void method() {

int local_Var = 90;// local variable


}

53
• 1) Local variables
• Local java variables can be declared within
methods, constructors, or blocks.
• Local variables are created when the method,
constructor or block is entered and the variable
will be destroyed once it exits the method,
constructor or block.
• Access modifiers cannot be used for local
variables Because Local Variables defined within
method.
• Local variable can be declared within the
method, constructor or block.
54
2) Instance variables
• Instance java variables are declared in a class, but
outside a method, constructor etc.
• When a space is allocated for an object in the heap, a
memory slot for each instance variable value is
created.
• Instance variables are created when an object is
created and destroyed when the object is destroyed.
• Instance variables hold values that must be
referenced by more than one method, constructor or
block.
• Access modifiers can be given for instance variables.

55
• Class / static variables
• class java variables is also referred to as static
variable and declared with the static key-word
in a category, but it is outside a method,
constructor or a block.
• only one replica of every class variable is
created, regardless of how many objects are
created.
• Static variables are stored in static memory.
• Static variables are created while the program
begins and destroyed while this system stops.
56
Java Operators
• An operator is used to perform an operation
over one or more operands.
• An operator is a character that represents an
action, for example + is an arithmetic operator
that represents addition.
• Java operators use in within class.

57
Types of Operator in Java
• Basic Arithmetic Operators
• Assignment Operators
• Auto-increment and Auto-decrement
Operators
• Logical Java Operators
• Comparison (relational) operators
• Bitwise Operators

58
Java Decision making statements
1) if Statement
2) if…else Statement
3) if…else…if…else Statement
4) Nested if statement
5) switch statement

59
if Statement

public class If_Java {

public static void main(String args[]) {

int x = 10;
if (x == 10) {

System.out.print("This is if statement");

}
}
}
60
if… else Statement

public class If_Else_Java {

public static void main(String args[]) {

int x = 30;

if (x == 20) {
System.out.print("This is if statement");

} else {
System.out.print("This is else statement");

}
}
}
61
if… else…if… else Statement

public class If_Else_If_Java {

public static void main(String args[]) {

int x = 30;

if (x == 10) {
System.out.print("Value of X is 10");

} else if (x == 20) {
System.out.print("Value of X is 20");

} else if (x == 30) {
System.out.print("Value of X is 30");

} else {
System.out.print("This is else statement");

}
}
}

62
switch statement

• A switch decision making statement allows a variable


to be tested against a list of values.
• Each value is called a case and the variable is being
checked for each case.The body of a switch statement
is referred to as a switch block.
• A statement in the switch block can be categorized
with one or greater case or default labels.
• The switch statement evaluates its expression, then
executes all statements that follow the matching case
label.
63
public class Switch_Java {

public static void main(String args[]) {

char grade = 'D';


switch (grade) {

case 'A':
System.out.println("Excellent!");
break;

case 'B':

case 'C':
System.out.println("Well done");
break;

64
case 'D':
System.out.println("You passed");
break;

case 'F':
System.out.println("Better try again");
break;

default:
System.out.println("Invalid grade");

}
}
}
65
Java Loop
• In some situation you need to execute a block of code several
number of times in such a case loops are used.
• A java loop statement permits us to execute
a statement or group of statements multiple times and following
is the general form of a loop statement in most of the
programming languages.
• Looping in programming languages is
a characteristic which helps the execution of a
set of instructions/functions again and again while a
few situation evaluates to true.
• Java provides three methods for executing the loops.
• while all the approaches offer similar simple capability,
they range of their syntax and condition checking time.
66
• while Loop
• do…while Loop
• for Loop
• for each loop
• Java Continue Statement
• Java Break Statement

67
The while Loop:
• A while loop is a control shape that allows you to
repeat a assignment for sure number of times.
• while executing, if the condition is actual, then
the actions inside the loop might be done.
• This could retain as long as the condition is true.
• While loop begins with the checking of situation. If it
evaluated to actual, then the java
loop body statements are executed in any other
case first statement following the loop is achieved.
• For that reason it is also referred to
as access control loop
68
Syntax:

while (condition)
{
//Statements
}
Example:

public class While_Java {

public static void main(String args[]) {


int x = 10;
while (x < 15) {
System.out.print("value of x : " + x);
x++;
System.out.print("\n");
}
}
}
69
The do…while Loop

• A do…while loop is much like a


while loop, besides that a do…while loop is assured to
execute as a minimum one time.
• The situation appears on the end of the loop, so the
statements within the java loop execute as soon
as before the condition is examined.
• If the condition is proper,
the flow of control jumps returned as much as do,
and the statements in the loop execute once more.
• This can hold so long as the condition is actual.
70
Syntax:
do
{
//Statements
}while(condition);

Example:
public class Do_While_Java {
public static void main(String args[]) {
int x = 10;
do {
System.out.print("value of x : " + x);
x++;
System.out.print("\n");
} while (x < 13);
}
}

71
The for Loop

• for loop is a repetition control structure that


execute a particular number of times.
• for loop is useful when you recognize how in
many instances a task is to be repeated.

72
• Syntax:

for(initialization;condition;increment/decrement)
{
//
}
• Example:

public class For_Java {


public static void main(String args[]) {
for (int x = 10; x < 13; x = x + 1) {
System.out.print("value of x : " + x);
System.out.print("\n");
}
}
}
73
The for each Loop

• It is particularly used to traverse array


or collections in Java.
• The gain of for-every java loop is that
it eliminates the opportunity of bugs and makes
the code extra readable.
• Syntax:
for(data_type variable : (array or collection)){
//...
}
74
class For_Each_Java {
public static void main(String args[]) {
int arr[] = { 12, 13, 14, 44 };

for (int i : arr) {


System.out.println(i);
}
}
}
75
class ForEachExample1{
public static void main(String args[]){
int arr[]={12,13,14,44};
int total=0;
for(int i:arr){
total=total+i; }
System.out.println("Total: "+total);
}
}
76
Java Continue Statement

• The Java continue statement is used to continue loop


until statement is true.
• It continues the current float of this system and skips
the remaining code at special condition.
• In case of internal loop, it continues only internal loop.
Syntax:

jump-statement;
continue;

77
Example
public class Continue_Java {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}
}
}
78
Java Break Statement

• The Java break is used to break loop


or switch statement until statement is true or false.
• It breaks the current go with the flow of this
system at exact condition.
• In case of internal loop, it breaks only internal loop.
• Syntax
jump-statement;
break;

79
Example
public class Break_Java {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
}
}
80
Arrays
• The array is a collection of elements of the same type that are
nearby memory spaces.
• We can store only a certain set of elements in a java array.
• The array index is based, the first element of the array is stored in
the 0 index.
Types of Array:
• One Dimensional Array
• Two Dimensional Array
Java program contains steps in array:
• Announce the name of the array.
• Create an array.
• Start array values.
81
One dimensional array

Syntax:
• dataType[] arr; (or)
• dataType []arr; (or)
• dataType arr[];

• An array declaration has two components: array type and array name.
• The type of an array is written as type [], where type elements are the
type of data; Brackets are special symbols which indicate that this
variable holds an array.
• The size of the array is not part of its type.
• With other types of variables, the announcement does not actually
make a Java array; It only tells the compiler that in this variable there
will be an array of the specified type.
82
//
Java Program to illustrate how to declare, instantiate
, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//
length is the property of array
System.out.println(a[i]);
}} 83
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}

84
• Another way of creating and initializing same
one dimensional array is as shown below.

int a[]={10,20,70,40,50};

85
Two Dimensional Array

• In the Java software development language,


two-dimensional array is like a spreadsheet
with multiple rows and columns, each with
different data in each slot.
• Each cell will be identified by its unique line
and column index combination (e.g. SR 1 [3]
[2]).
• We can use a two-dimensional array to store
user IDs and passwords of different users.
86
Syntax
• dataType[][] arrayRefVar; (or)

• dataType [][]arrayRefVar; (or)

• dataType arrayRefVar[][]; (or)

• dataType []arrayRefVar[];
87
public class Two_Array_Java {

public static void main(String[] args) {

String str[][] = new String[3][2]; // 3 rows, 2 columns

str[0][0] = "user_1";
str[1][0] = "user_2";
str[2][0] = "user_3";
str[0][1] = "pwd_1";
str[1][1] = "pwd_2";
str[2][1] = "pwd_3";

// This for loop will be total executed 3 times.


for (int i = 0; i < str.length; i++) {

// for loop will be executed for 2 time every iteration.


for (int j = 0; j < str[i].length; j++) {

System.out.println(str[i][j]);

} }
88
}
Command Line Arguments

• Command Line Argument in Java is the information that is


passed to the program when it is executed.
• The information passed is stored in the string array passed to
the main() method and it is stored as a string.
• It is the information that directly follows the program’s name
on the command line
• The command-line arguments in Java allow us to pass
arguments during the execution of the program, when it is
running.

89
class Main
{
public static void main(String[] args)
{ System.out.println("Command-Line arguments are");
// loop through all arguments
for(String str: args)
{
System.out.println(str);
}
}
}
90
1. To compile the code
javac Main.java
2. To run the code
java Main
• Now suppose we want to pass some arguments while running
the program, we can pass the arguments after the class name.
• For example,
java Main apple ball cat
• Here apple, ball, and cat are arguments passed to the
program through the command line.
• Now, we will get the following output.
Command-Line arguments are Apple Ball Cat
• In the above program, the main() method includes an array of
strings named args as its parameter.
• Note: Arguments are always stored as strings and always
separated by white-space. 91
Passing Numeric Command-Line Arguments

• The main() method of every Java program only


accepts string arguments.
• Hence it is not possible to pass numeric
arguments through the command line.
• However, we can later convert string
arguments into numeric values.

92
Example: Numeric Command-Line Arguments

class Main
{
public static void main(String[] args)
{
for(String str: args)
{ // convert into integer type
int argument = Integer.parseInt(str);
System.out.println("Argument in integer form: " + argument);
}
}
}
93
// compile the code
javac Main.java
// run the code
java Main 11 23
Here 11 and 23 are command-line arguments.
Now, we will get the following output.
Arguments in integer form 11 23

94
• In the above example, notice the line
int argument = Integer.parseInt(str);
• Here, the parseInt() method of the Integer class converts the
string argument into an integer.
• Similarly, we can use
the parseDouble() and parseFloat() method to convert the
string into double and float respectively.
• Note: If the arguments cannot be converted into the specified
numeric value then an exception
named NumberFormatException occurs.

95
Java Methods
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also
known as functions.
• Why use methods? To reuse code: define the code once, and use
it many times.
• A method must be declared within a class.
• It is defined with the name of the method, followed by
parentheses ().
• In Java, there are two types of methods:
• User-defined Methods: We can create our own method based on
our requirements.
• Standard Library Methods: These are built-in methods in Java that
are available to use.
• Java provides some pre-defined methods, such 96
• We can also create your own methods to perform certain
actions:

public class Main


{
static void myMethod()
{
// code to be executed
}
}

97
• 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.
• void means that this method does not have a return value.

98
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:
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}
} 99
With Parameters
public class Main
{
static void myMethod(String fname, int age)
{
System.out.println(fname + " is " + age);
}
public static void main(String[] args)
{
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
} 100
Return Values
• The void keyword, used in the examples above, indicates that the
method should not return a value.
• If you want the method to return a value, you can use a primitive
data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method .
public class Main
{
static int myMethod(int x)
{
return 5 + x;
}
public static void main(String[] args)
{ System.out.println(myMethod(3));
}
}
101
Method Overloading
• With method overloading, multiple methods can have the
same name with different parameters.
Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

102
static int plusMethodInt(int x, int y)
{
return x + y;
}
static double plusMethodDouble(double x, double y)
{ return x + y;
}
public static void main(String[] args)
{
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
103
Example-2
class MethodOverloading
{
private static void display(int a)
{
System.out.println("Arguments: " + a);
}
private static void display(int a, int b)
{
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args)
{
display(1);
display(1, 4);
} 104
Important Points
• Two or more methods can have the same
name inside the same class if they accept
different arguments. This feature is known as
method overloading.
• Method overloading is achieved by either:
– changing the number of arguments.
– or changing the data type of arguments.
• It is not method overloading if we only change
the return type of methods. There must be
differences in the number of parameters.
105
Constructor
• A Java constructor is special method that is called when an
object is instantiated.
• In other words, when you use the new keyword.
• The purpose of a Java constructor is to initializes the newly
created object before it
class Test
{
Test()
{
// constructor body
}
}
• Here, Test() is a constructor. It has the same name as that of
the class and doesn't have a return type. 106
Example
class Main
{
private String name;
// constructor
Main()
{
System.out.println("Constructor Called:");
name = “XXXXX";
}
public static void main(String[] args)
{ // constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}} 107
Types of Constructor

In Java, constructors can be divided into 3 types:


• No-Arg Constructor
• Parameterized Constructor
• Default Constructor

108
1. Java No-Arg Constructors

• Similar to methods, a Java constructor may or


may not have any parameters (arguments).
• If a constructor does not accept any
parameters, it is known as a no-argument
constructor. For example,
private Constructor()
{
// body of the constructor
}
109
class Main
{ int i;
// constructor with no parameter
Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args)
{
// calling the constructor without any parameter
Main obj = new Main();
System.out.println("Value of i: " + obj.i);

}} 110
2. Java Parameterized Constructor

• A Java constructor can also accept one or more parameters.


Such constructors are known as parameterized constructors
(constructor with parameters).

111
class Main
{ String languages;
// constructor accepting single value
Main(String lang)
{
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args)
{ // call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}}
112
3. Java Default Constructor
• If we do not create any constructor, the Java compiler
automatically create a no-arg constructor during the execution
of the program. This constructor is called default constructor.
class Main
{ int a;
boolean b;
public static void main(String[] args)
{
// A default constructor is called
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}} 113
The default constructor initializes any uninitialized instance variables with
default values.

Type Default Value


boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d

114
Important Notes on Java Constructors
• Constructors are invoked implicitly when you instantiate objects.
• The two rules for creating a constructor are:
The name of the constructor should be the same as the class.
A Java constructor must not have a return type.
• If a class doesn't have a constructor, the Java compiler automatically
creates a default constructor during run-time. The default constructor
initializes instance variables with default values. For example,
the int variable will be initialized to 0
• Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the
Java compiler if it is not explicitly defined.
• A constructor cannot be abstract or static or final.
• A constructor can be overloaded but can not be overridden.

115
Constructors Overloading in Java
• Similar to Java method overloading, we can also create two or
more constructors with different parameters. This is called
constructors overloading.

116
class Main
{ String language;
// constructor with no parameter
Main()
{ this.language = "Java";
}
// constructor with a single parameter
Main(String language)
{
this.language = language;
}
public void getName()
{ System.out.println("Programming Langauage: " + this.language);
} public static void main(String[] args)
{ // call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}}

117
Implicit this
• In Java, this keyword is used to refer to the current object inside a
method or a constructor. For example,
class Main
{
int instVar;
Main(int instVar)
{
this.instVar = instVar;
System.out.println("this reference = " + this);
}
public static void main(String[] args)
{ Main obj = new Main(8);
System.out.println("object reference = " + obj);
System.out.println("object reference = " + obj.instVar);
}} 118
Output
this reference = Main@23fc625e
object reference = Main@23fc625e

• In the above example, we created an object


named obj of the class Main. We then print the
reference to the object obj and this keyword of the
class.
• Here, we can see that the reference of
both obj and this is the same. It means this is
nothing but the reference to the current object.
119
static
members
• Variables and methods declared using keyword static are
called static members of a class. You know that non-
static variables and methods belong to instance. But
static members (variables, methods) belong to class.
Static members are not part of any instance of the class.
Static members can be accessed using class name
directly, in other words, there is no need to create
instance of the class specifically to use them.
Static members can be of two types:
#Static Variables
#Static Methods
120
Static Variables

• Static variables are also called class variables because


they can be accessed using class name, whereas, non
static variables are called instance variables and can
be accessed using instance reference only.
• Static variables occupy single location in the memory.
These can also be accessed using instance reference.
These are accessible in both static and non-static
methods, even non-static methods can change their
values.

121
Static Methods/Class Methods

• Static methods are also called class methods. A static


method belongs to class, it can be used with class
name directly. It is also accessible using instance
references.

Static methods can use static variables only, whereas


non-static methods can use both instance variables
and static variables.

Generally, static methods are used to perform some


common tasks for all objects of a class.
122
class Student
{
private static int count=0; //static variable
Student()
{
count++; //increment static variable }
static void showCount() //static method
{
System.out.println(“Number Of students : “+count);
}}
public class StaticDemo
{
public static void main(String[] args)
{ Student s1=new Student();
Student s2=new Student();
Student.showCount(); //calling static method
Student s3=new Student();
Student s4=new Student(); 123
• Output:
Number of students : 2
Number of students : 4
Explanation:
In the above program, constructor function
increments the static variable (count) on creation of
new object of Student class. The program also
consists a static method i.e. showCount(), which is
invoked to get number of objects of Student class in
memory.
124
Access Modifiers
• The access modifiers in java define accessibility (scope) of variable,
method, constructor or class.
• There are 4 types of java access modifiers
1)private
2)default/No modifier
3) protected
4) public
• Java addresses four categories of visibility for class members:
1) Subclasses in the same package
2) Non-subclasses in the same package.
3) Subclasses in different packages.
4) Classes that are neither in the same package nor subclasses. No
relation between the classes.
125
Scanner Class in Java

• Scanner is a class in java.util package used for obtaining


the input of the primitive types like int, double etc. and
strings.
• To create an object of Scanner class, we usually pass the
predefined object System.in, which represents the
standard input stream. We may pass an object of class File
if we want to read input from a file.
• To read strings, we use nextLine().
• To read a single character, we use next().charAt(0). next()
function returns the next token/word in the input as a
string and charAt(0) funtion returns the first character in
that string. 126
Following are the important points about Scanner −
• A Scanner breaks its input into tokens using a delimiter
pattern, which by default matches whitespace.
• A scanning operation may block waiting for input.
• A Scanner is not safe for multithreaded use without
external synchronization.
• To use the Scanner class, create an object of the class
and use any of the available methods found in
the Scannerclass documentation. In our example, we
will use the nextLine() method, which is used to read
Strings
127
Example
import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a
Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user
input
System.out.println("Username is: " + userName);
}}
128
Input Types

• In the example above, we used the nextLine() method, which is used to


read Strings. To read other types, look at the table below:

Method Description
nextBoolean() Reads a boolean value from the
user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

129
• import java.util.Scanner;

class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
130
}

You might also like