Java I

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 47

SCHOOL OF ARTS AND SCIENCE

DEPARTMENT OF COMPUTATIONAL
STUDIES
UNIT-I
PROBLEM SOLVING USING JAVA

Dr. ANTONY PAUL RAJ.A M.Sc., M.Phil., B.Ed., Ph.D


Assistant Professor
Department of Computational Studies
School of Arts and Science, SMVEC
UNIT-I
INTRODUCTION TO JAVA PROGRAMMING

The History and Evolution of Java – Byte code – Java buzzwords –


Data types – Variables – Arrays –operators – Control statements –
Type conversion and casting- Basic Concepts of OOPs – Concepts
of classes and objects - Constructors – static keyword – Final with
data – Access control – This key word –Garbage collection –
Nested classes and inner classes – String class.
History of Java:
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.

2) Initially it was designed for small, embedded systems in electronic appliances like set-
top boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project. Why
Java was named as "Oak"? Java History from Oak to Java

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Evolution of java:
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 18 (to be released by March 2022)
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.
Java Buzzwords or Features of Java

 Simple
 Object-oriented
 Distributed
 Interpreted
 Robust
 Secure
 Architecture neutral
 Portable
 High performance
 Multithreaded
 Dynamic
1. Simple:
• Java was designed to be easy for a professional programmer to learn and
use
• effectively.
• It’s simple and easy to learn if you already know the basic concepts of Object
• Oriented Programming.
2. Object Oriented

• Java is true object-oriented language.


• Almost “Everything is an Object” paradigm. All program code and data
reside within
• objects and classes.
• The object model in Java is simple and easy to extend.
• Java comes with an extensive set of classes, arranged in packages that can
be used in
• our programs through inheritance.
3. Distributed

• Java is designed fa or distributed environment of the Internet. Its used for creating
applications on networks.
• Java applications can access remote objects on the Internet as easily as they can do in
the local system.
• Java enables multiple programmers at multiple remote locations to collaborate and
• work together on a single project.
4. Compiled and Interpreted

• Usually, a computer language is either compiled or Interpreted. Java combines both this
approach and makes it a two-stage system.
• Compiled: Java enables the creation of cross-platform programs by compiling into an
• intermediate representation called Java Bytecode.
5. Robust

• It provides many features that make the program execute reliably in a variety of environments.
• Java is a strictly typed language. It checks code both at compile time and runtime.
• Java takes care of all memory management problems with garbage collection.
6. Secure

• Java provides a “firewall” between a networked application and your computer.


• When a Java Compatible Web browser is used, downloading can be done safely
• without fear of viral infection or malicious intent.
7. Architecture Neutral

• Java language and Java Virtual Machine helped in achieving the goal of “write once;
• run anywhere, any time, forever.”
• Changes and upgrades in operating systems, processors and system resources will not
• force any changes in Java Programs.
8. Portable
• Java Provides a way to download programs dynamically to all the various types of platforms
connected to the Internet.
• It helps in generating Portable executable code.
9. 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.
10. Multithreaded
• Multithreaded Programs handled multiple tasks simultaneously, which was helpful in creating
interactive, networked programs.
11. Dynamic
• Java is capable of linking in new class libraries, methods, and objects.
• Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at runtime.
DATA TYPES

Data types specify the different sizes and values that can be stored
in the variable. There are two types of data types in Java:

Primitive data types: The primitive data types include boolean,


char, byte, short, int, long, float and double.

Non-primitive data types: The non-primitive data types include


Classes, Interfaces, and Arrays
Byte Data Type:
• Byte data type is a 8-bit signed two.s complement integer. Minimum value is -128 (-2^7)
• Maximum value is 127 (inclusive)(2^7 -1). Default value is 0

Short Data Type:


• Short data type is a 16-bit signed two's complement integer. Minimum value is -32,768 (-
2^15)
• Maximum value is 32,767(inclusive) (2^15 -1). Short data type can also be used to save
memory as byte data type. A short is 2 times

Int Data Type


• Int data type is a 32-bit signed two's complement integer.
• Minimum value is - 2,147,483,648.(-2^31)
• Maximum value is 2,147,483,647(inclusive).(2^31 -1)
• Int is generally used as the default data type for integral values unless there is a concern
about memory.
Long Data Type
• Long data type is a 64-bit signed two's complement integer.
• Minimum value is -9,223,372,036,854,775,808.(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive).

Float Data Type:


• Float data type is a single-precision 32-bit IEEE 754 floating point.
• Float is mainly used to save memory in large arrays of floating point numbers.
• Default value is 0.0f

Double Data Type


• Double data type is a double-precision 64-bit IEEE 754 floating point.
• This data type is generally used as the default data type for decimal values. generally the
default choice.
JAVA
VARIABLES
A variable is the name of a reserved area allocated in memory. In
other words, it is a name of the memory location. It is a combination
of "vary + able" which means its value can be changed.
Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variables
1) Local Variable:
 A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware
that the variable exists.
 A local variable cannot be defined with "static" keyword.
2) Instance Variable:
 A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
 It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable:
 A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
 Memory allocation for static variables happens only once when the class is loaded in the
memory.
JAVA ARRAYS:

• Normally, an array is a collection of similar type of elements which has contiguous memory
location.

• Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements
• in a Java array.

• Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.Unlike C/C++, we can get the length of the array using
the length member. In C/C++,
• we need to use the sizeof() operator.
OPERATORS IN JAVA

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
JAVA CONTROL STATEMENTS | CONTROL FLOW IN
JAVA
Decision-Making statements:
1) If Statement:

The Java if statement is used to test the condition. It checks boolean


condition: true or false.
There are various types of if statement in Java.
 if statement
 if-else statement
 if-else-if ladder
 nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is
true.
Syntax:
if(condition){
//code to be executed }
if-else Statement:

The Java if-else statement also tests the condition. It executes the if
block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
if-else-if ladder Statement:
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Nested if statement:

The nested if statement represents the if block within another if block. Here, the
inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
LOOPING:
for Loop:
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
 Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
 Condition: It is the second condition which is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return boolean
value either true or false. It is an optional condition.
 Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
 Statement: The statement of the loop is executed each time until the second condition
is false.

for(initialization; condition; increment/decrement){


//statement or code to be executed }
for-each Loop:

The for-each loop is used to traverse array or collection in Java. It is easier


to use than simple
for loop because we don't need to increment value and use subscript
notation.
It works on the basis of elements and not the index. It returns element one
by one in the
defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
WHILE LOOP:
The Java while loop is used to iterate a part of the program repeatedly until
the
specified Boolean condition is true. As soon as the Boolean condition
becomes false,
the loop automatically stops.
The while loop is considered as a repeating if statement. If the number of
iteration is
not fixed, it is recommended to use the while loop.
Syntax:
while (condition){
//code to be executed
Increment / decrement statement ;
}
do-while Loop:
The Java do-while loop is used to iterate a part of the program repeatedly, until
the
specified condition is true. If the number of iteration is not fixed and you must
have to
execute the loop at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop
and for
loop, the do-while check the condition at the end of loop body. The Java do-
while
loop is executed at least once because condition is checked after loop body.
Syntax:
do{
}while (condition);
Continue Statement
The continue statement is used in loop control structure when you need to jump
to the next
iteration of the loop immediately. It can be used with for loop or while loop.
SYNTAX:
jump-statement;
continue;
Break Statement
When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following
the
loop.
Syntax:
jump-statement; break;
TYPE CONVERSION AND CASTING
In Java, type casting is a method or process that converts a data type into
another data type in
both ways manually and automatically. The automatic conversion is done by the
compiler
and manual conversion performed by the programmer. Type Casting in Java
Types of Type Casting

There are two types of type casting:


o Widening Type Casting
o Narrowing Type Casting
Widening Type Casting

Converting a lower data type into a higher one is called widening type casting. It is also known as implicit
conversion or casting down. It is done automatically. It is safe because there is no chance to lose data. It
takes place when:
 Both data types must be compatible with each other.
 The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If we do
not perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
BASIC CONCEPTS OF OOPS:
OOPs (Object-Oriented Programming System):

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object
Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some
concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
METHODS DECLARATION
 A class with only data fields has no life.
 The objects created by such a class cannot respond to any messages.
 We must therefore and methods that are necessary for manipulating
 The data contained in the class.
 Methods are declared inside the body of the class but immediately after the declaration
of instance variables.
 The general form of a methods declaration is
Type method_name ( parameter-list )
{
Method-body;
}
 Method declarations have four basic parts:
 The name of the method(method name)
 The type of the value the method returns(type)
 A list of parameters(parameter-list)
 The body of the method
Constructors in Java:

 In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is called.
 It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides
a default constructor by default.
 There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Rules for creating Java constructor:

There are two rules defined for the constructor.


 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Java static variable
the declaration any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
Final Keyword In Java:

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
• variable
• method
• class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only.
Access Modifiers (access control):

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
this keyword :

In Java, this is a reference variable that refers to the current object.


Here is given the 6 usage of java this keyword.
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
Java Garbage Collection:
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management. There are many ways:
1) By nulling the reference
2) By assigning a reference to another
3) By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();
finalize() method:

The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class
as:

protected void finalize(){}

gc() method :

The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

public static void gc(){}


Java Inner Classes (Nested Classes):
 Java inner class or nested class is a class that is declared inside the class or
interface.
 We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
 Additionally, it can access all the members of the outer class, including private
data members and methods.

Syntax of Inner class :


class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Types of Nested classes:
There are two types of nested classes non-static and static nested classes. The non-static nested classes are
also known as inner classes.
 Non-static nested class (inner class)
1) Member inner class
2) Anonymous inner class
3) Local inner class
 Static nested class

Java Member Inner class


A non-static class that is created inside a class but outside a method is called member inner class. It is also known as a
regular inner class. It can be declared with access modifiers like public, default, private, and protected.

Syntax:
class Outer{
//code
class Inner{
//code
}
}
Java Anonymous inner class
Java anonymous inner class is an inner class without a name and for which only a single object
is created. An anonymous inner class can be useful when making an instance of an object with
certain "extras" such as overloading methods of a class or interface, without having to actually
subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface.

Java Local inner class


A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are
the inner classes that are defined inside a block. Generally, this block is a method body.
Sometimes this block can be a for loop, or an if clause. Local Inner classes are not a member of
any enclosing classes. However, they can be marked as final or abstract. These classes have
access to the fields of the class enclosing it.
String
String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
There are two ways to create String object:
1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes.


For Example:
String s="welcome";
1. String s1="Welcome";
2. String s2="Welcome";

2) By new keyword

String s=new String("Welcome


Java String class methods
The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
Thank
you

You might also like