Java M1
Java M1
Chethan Raj C
Assistant Professor & HoD,
Dept of CSE
MODULE-01
An Overview of Java
Object-Oriented Programming (Two Paradigms, Abstraction, The Three OOP Principles).
Using Blocks of Code
Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators, The Java Keywords).
Data Types
Variables and Arrays
The Primitive Types (Integers, Floating-Point Types, Characters, Booleans)
Type Conversion and Casting— Refer class notes
Automatic Type Promotion in Expressions-- Refer class notes
Arrays
Introducing Type Inference with Local Variables.
Operators
Operator Precedence
Using Parentheses.
Control Statements Refer class notes
Java‘s Selection Statements (if, The Traditional switch) Refer class notes
Iteration Statements (while, do-while, for, The For-Each Version of the for Loop, Local Variable Type Inference in a for Loop,
Nested Loops) Refer class notes
Jump Statements (Using break, Using continue, return). Refer class notes
Programming
It is a Set of instruction / Group of instruction.
Programming Language
A Language which is used to communicate between user and system. Ex: C, C++, Java, Python etc.
An Overview of Java
Java is a general-purpose and object-oriented programming language developed for the distributed environment and software development
for consumer electronic devices such as TVs, VCRs, toasters, etc.
Java Programming Language is a platform-independent language, which means there is no limitation to any particular hardware or
operating system. It provides users the facility to ‗write once, run anywhere‘(WORA). Many operating systems such as Sun Solaris,
RedHat, Windows, etc., support Java.
Java is a concurrent, class-based, and object-oriented language. It is freely accessible, and we can run it on all the platforms or the operating
systems. Java is simple and easy to learn.
Ex: Java Hello World Example
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("HelloWorld!");
}
}
Two Paradigms
In General all computer programs consist of two elements: code and data. Furthermore, a program can be conceptually organized around
its code or around its data. That is, some programs are written around ―what is happening and others are written around ―who is being
affected. These are the two paradigms that govern how a program is constructed. The first way is called the process-oriented model. This
approach characterizes a program as a series of linear steps (that is, code). The process-oriented model can be thought of as code acting on
data. Procedural languages such as C employ this model. Problems with this approach appear as programs grow larger and more complex
and to manage program is increasing in complexity. The second approach, called object-oriented programming, where Object-oriented
programming(OOP) organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-
oriented program can be characterized as data controlling access to code as by switching the controlling entity to data, you can achieve
several organizational benefits.
Procedure oriented Programming (POP): In this approach, the problem is always considered as a sequence of tasks to be done. A
number of functions are written to accomplish these tasks. Here primary focus on ―Functions‖ and little attention on data. There are many
high level languages like COBOL, FORTRAN, PASCAL, C used for conventional programming commonly known as POP. POP basically
consists of writing a list of instructions for the computer to follow, and organizing these instructions into groups known as functions.
Normally a flowchart is used to organize these actions and represent the flow of control logically sequential flow from one to another. In a
multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function
may have its own local data. Global data are more vulnerable to an in advent change by a function. In a large program it is very difficult to
identify what data is used by which function. In case we need to revise an external data structure, we should also revise all the functions
that access the data.
Drawback: It does not model real world problems very well, because functions are action oriented and do not really corresponding to the
elements of the problem.
Chethan Raj C, HoD, Dept of CSE Page 4
Object Oriented Programming using JAVA
Characteristics of POP:
1. Emphasis is on doing actions.
2. Large programs are divided into smaller programs known as functions.
3. Most of the functions shared global data.
4. Data move openly around the program from function to function.
5. Functions transform data from one form to another.
6. Employs top-down approach in program design.
Characteristics of OOP:
1. Emphasis on data .
2. Programs are divided into what are known as methods.
3. Data structures are designed such that they characterize the objects.
4. Methods that operate on the data of an object are tied together .
5. Data is hidden.
6. Objects can communicate with each other through methods.
7. Code Reusability.
8. Follows bottom-up approach in program design.
History of JAVA
Java is started by company called as Sun microsystem.
Java currently owned company called as Oracle.
Java is invented by person called as James Gosling.
The first name of Java was Green talk but the name was not so popular so renamed as oak in the year 1991 but the name was already
registered by some other company later it is renamed as Java in the year 1994-95 and coffee mug is the sign of symbol for JAVA.
Introduction to Java
Java is an object oriented language, complete java language is built on classes and object. Java is also known as a strong Object-oriented
programming language(oops). OOPS is a programming approach which provides solution to problems with the help of algorithms based on
real world. It uses real world approach to solve a problem. So object oriented technique offers better and easy way to write program then
procedural programming model such as C, ALGOL, PASCAL. Object oriented languages has 2 building blocks i) class -> template of an
object ii) object -> a real world or an instance of a class In Java everything is encapsulated under classes. Class is the core part of the Java
language. Object-Oriented Programming is a strategy or a style of developing applications or developing software. It is a methodology.
Other methodologies are also there like Structured Programming, Procedural Programming, Modular Programming. or Aspect-Oriented
programming. But nowadays, one of the well-known and famous styles is Object Orientation. Nowadays, all the latest programming
languages support object orientation and this object orientation is more related to the designing of software and this deals with internal
design but not external that is visible designing. So, it is nowhere related to the users of the software, it is related to the programmers who
are working on developing software.
Abstraction
Abstraction is the process of hiding the internal and secured details and showing just the functionality. Abstraction can be achieved through
abstract class or interface in Java. Hiding internal details and showing required functionality is known as abstraction.
For example: In phone call, user don't know the internal processing. In java, user use abstract class and interface to achieve abstraction.
Hiding the Implementations from the User which are not necessary, and showing the necessary details to the user i.e., method names,
parameters, returns types. Abstraction is achieved by using interfaces, interfaces will have only method declarations, it suggests what
method does but doesn‗t suggest how it is implemented. So that the implementation is done by somebody else and interfaces are used other
developers
1. Abstract classes offer default functionality for the subclasses.
2. Provides a template for future specific classes
3. Helps user to define a common interface for its subclasses
4. Abstract class allows code reusability.
The Java's smallest unit of abstraction is class. Because of the interplay between the classes and packages, Java addresses the following four
categories of visibility for class members :
1. Subclasses in same package
2. Non-subclasses in same package
3. Subclasses in different packages
4. Classes that are neither in same package nor in subclasses.
3. Secure
Java goes to the great security issues by putting in place multilevel system of security.
First at the compile time pointers and memory allocation are removed even though the java compiler produces only correct java code
there is still the possibility of the code being tempered with between compilation and runtime. java guards against this by using bytecode
Verifier to check the bytecode for language compliance when the code fist enters the interpreter before it gets the chance to run. It also
specifies following things that the code does not do any of the following.
Forge pointers
Violate access restrictions
Incorrectly access classes
Overflow or underflow operand stack
Use incorrect parameters of bytecode instructions
Use illegal data conversions
Second at run time the java interpreter further ensures that classes loaded do not access the file system except in the manner permitted
by the client Or the user.
Sun Microsystems adds another dimension to the security of java. They are currently working on public key encryption system to allow
java applications to be stored and transmitted over the internet in a secure encrypted form.
The Java language supports many high-performance feature such as multithreading, just-in-time compiling, and native code usage.
Java has employed multithreading to help overcome the performance problems suffered by interpreted code as compared to native code.
Since an executing program hardly ever uses CPU cycles 100 % of the time, Java uses the idle time to perform the necessary garbage
cleanup and general system maintenance that renders traditional interpreters slow in executing applications. [Note: Multithreading is the
ability of an application to execute more than one task (thread) at the same time e.g. a word processor can be carrying out spell check in one
document and printing a second document at the same time.
5. Platform Independent
A program or technology is said to be platform independent if and only if which can run on all available operating systems with respect to
its development and compilation. (Platform represents O.S).
Platform independent: Java programs use the Java virtual machine as abstraction and do not access the operating system directly. This
makes Java programs highly portable. A Java program (which is standard-compliant and follows certain rules) can run unmodified on all
supported platforms, e.g., Windows or Linux.
6. Architectural Neutral
A Language or Technology is said to be Architectural neutral means, which can run on any available processors in the real world without
considering their development and compilation with other specifications and requirements as ―write once; run anywhere, any time,
forever.‖(WORA).
7. Portable
If any language supports platform independent and architectural neutral feature known as portable. The languages like C, CPP, Pascal are
treated as non-portable language. It is a portable language.
•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.
8. Multithreaded
Java was designed to meet the real world requirement by creating interactive networked programs.
Java programs can do many things simultaneously.To accomplish this java support multithreaded programming which allows user to write
programs that does many things and tasks simultaneously.
A flow of control is known as a thread i.e single line of execution in program. When any Language executes multiple thread at a time that
language is known as multithreaded. Java‘s easy-to-use approach to multithreading allows to work on specific behaviour of the program,
not the multitasking subsystem.
9. Distributed
Java is designed for the environment of internet because it handles TCP\IP protocol and be able to access files on the internet as easily,as
writing to a local file system.
Java also allows objects on two different computers to execute procedures remotely. java has recently revised this interfaces in a package
called Remote Method Invocation(RMI).
10. Networked
It is mainly designed for web based applications, J2EE is used for developing network based applications.
11. Robust
Java is a robust language. It provides many safeguards to ensure reliable code. The ability to create robust programs was given a high
priority in the design of Java. Java is a strictly typed language; it checks the code at compile time. However, it also checks user code at run
time. In fact, many hard-to-track-down bugs that often turn up in hard-to-reproduce run-time situations are simply impossible to create in
Java.
There are two reasons for program failure
1. memory management mistakes
2. mishandled exceptional conditions
Java manages memory automatically by using garbage collector. Exception conditions are handled in java by providing object
exception handling. In the well written java program all runtime errors can and should be managed by the program.
Note: Robust simply means strong. It is robust or strong Programming Language because of its capability to handle Run-time Error,
automatic garbage collection, the lack of pointer concept, Exception Handling. All these points makes java robust Language.
12. Dynamic
13. Secure
It is a more secure language compared to other language; In this language, all code is covered in byte code after compilation which is not
readable by human.
Encapsulation:
The most adopted and popular programming language approach, structured programming approach, failed to show the desired results in
terms of bug-free, easy-to-maintain, and reusable programs.
The programming approach, Object-Oriented approach (OOP), offers a new and powerful way to cope with this complexity. The approach
of OOP is based on various concepts that help achieve its goal to overcome the drawbacks of structured programming approaches.
Encapsulation is one of the most powerful and fundamental concepts of Object-Oriented Programming. Encapsulation, in general, is the
action of enclosing or binding the data and member function. In OOP, it is a way of combining both data and functions that operate on that
data, into a single unit.
In other words, we can define it as Encapsulation is the wrapping up of data and functions (methods that operate on the data) into a single
unit (called class).
Note:
There is a prohibition for direct access to the data. Functions (that combine with the data) are the only way to access data. These functions are
the member functions or methods in Java. It basically creates a shield due to which the code or data cannot be accessed outside the shield.
Inheritance: Inheritance is a process of acquiring the properties, functionalities and behaviors defined in one class (Base class) into to
another class (Derived class). In java extends keyword is used for inheritance concept. Inheritance provides and achieves the reusability of
code from one class to another class.
• Is-A Relationship
• Has-A Relationship.
One of the advantages of an Object-Oriented programming language is code reuse. There are two ways user can do code reuse either by the
implementation of inheritance (IS-A relationship), or object composition (HAS-A relationship). Although the compiler and Java virtual
machine (JVM) confirms the use of inheritance, user can also get at the functionality of inheritance when user use composition.
Advantages:
1. The main purpose of the inheritance is code extensibility whenever user are extending automatically the code is reused.
2. In inheritance one class giving the properties and behavior and another class is taking the properties and behavior.
3. Inheritance is also known as is-a relationship means two classes are belongs to the same hierarchy
4. By using extends keyword user are achieving inheritance concept.
5. In the inheritance the person who is giving the properties is called parent the person who is taking the properties is called child.
6. To reduce length of the code and redundancy of the code the concept of inheritance is introduced.
Polymorphism
Polymorphism in Java is the task that performs a single action in different ways. So, languages that do not support polymorphism are not
‗Object-Oriented Languages‘, but ‗Object-Based Languages‘. Ada, for instance, is one such language. Since Java supports polymorphism,
it is an Object-Oriented Language.
Polymorphism occurs when there is inheritance, i.e., many classes are related. Inheritance is a powerful feature in Java. Java Inheritance
lets one class acquire the properties and attributes of another class. Polymorphism in Java allows us to use these inherited properties to
perform different tasks. Thus, allowing us to achieve the same action in many different ways. ―Poly‖ means numerous, and ―Morphs‖
means forms. So, polymorphism means innumerable forms. Polymorphism, therefore, is one of the most significant features of Object-
Oriented Programming.
Method Overloading is when a class has multiple methods with the same name, but the number, types, and order of parameters and the
return type of the methods are different. Java allows the user freedom to use the same name for various functions as long as it can
distinguish between them by the type and number of parameters
Runtime polymorphism in Java is also popularly known as Dynamic Binding or Dynamic Method Dispatch. In this process, the call to an
overridden method is resolved dynamically at runtime rather than at compile-time. You can achieve Runtime polymorphism via Method
Overriding.
Method Overriding is done when a child or a subclass has a method with the same name, parameters, and return type as the parent or the
superclass; then that function overrides the function in the superclass. In simpler terms, if the subclass provides its definition to a method
already present in the superclass; then that function in the base class is said to be overridden. Also, it should be noted that runtime
polymorphism can only be achieved through functions and not data members.
Overriding is done by using a reference variable of the superclass. The method to be called is determined based on the object which is being
referred to by the reference variable. This is also known as Upcasting.
Upcasting takes place when the Parent class‘s reference variable refers to the object of the child class.
1. Documentation Section
2. Package Statement
3. Import Statement
4. Interface Statement
5. Class Definition
6. Main Method Class
{
main Method Definition
}
Import Statement: After a package statement (but before any class definition)may be a number of import statement. This is similar to the
#include statement in C
Example: import java.util.Date;
This statement instructs the interpreter to load the Date class contained in the package util.
The benefits of organizing classes:
Compiler
Compiler is a system software and it checks any bugs is there in the program, if it find any bugs then compiler throw the compilation
error to the user and user should debug and sent the code back to the compiler to compile it for error free in a given source program,
this process will be repeated until it correct it, once compiler didn't found any mistake then the compiler is going to convert source
code into byte code and saved file name as (filename.class).
Byte code
Byte code is an intermediate code which is not understandable by machine nor by human beings and byte code a platform independent
which means byte code can be run in any operating system like windows, Linux, Mac, etc. with the help of JVM.
JDK: It is a collection of essential resources and software which is used for development of java application.
JRE (Java runtime environment): It will provide the environment for execution of Java program.
JVM (Java virtual Machine): It is used to convert bytecode into machine code with the help of JIT and interpreter.
Every Java Stand alone program requires a main method as its starting point.
o A Simple Java Program will contain only the main method class.
o It creates objects of various classes and uses those objects for performing various operations.
o When the end of main is reached the program terminates and the control transferred back to the Operating system.
main() method is the starting execution block of a java program or any java program to start their execution from main method. If any class
contain main() method known as main class.
Syntax of main() method:public static void main(String args[])
{
.......
.......
}
Public: This is the access modifier of main method. It has to be public so that java runtime can execute this method. Remember that if user
can make any method non-public then it‘s not allowed to be executed by any program, there are some access restrictions applied. So it
means that main method has to be public
public is a keyword in a java language whenever if it is preceded by main() method the scope is available anywhere in the java environment
i.e main() method can be executed from anywhere. main() method must be accessed by every java programmer and hence whose access
specifier must be public.
Static: When java runtime starts, there is no object of the class present. That‘s why main method has to be static, so that JVM can load the
class into memory and call the main method. If main method won‘t be static, JVM would not be able to call it because of there is no object
of the class is present.
void: void is a special datatype also known as no return type, whenever it is preceded by main() method that will be never return any value
to the operating system. main() method of java is not returning any value and hence its return type must be void.
String args[] String args[] is a String array used to hold command line arguments in the form of String values. User can change the order of
modifiers i.e Instead of String[] args. Java main method accepts a single argument of type String array. This is also called as java command
line arguments. The example of using java command line arguments.
Ex: public class Test
{
public static void main(String[] args)
{
for(String s : args)
{
System.out.println(s);
}
}
}
Printing Statement
1. System.out.println(data);
2. System.out.print(data);
println(): Print the data and cursor will be shifted into the next line.
print(): Print the data and cursor will be staying in the same line.
A code block is a section of code enclosed in curly braces {}. Code blocks are used to group one or more statements. Code blocks can be
nested, meaning you can have code blocks inside of other code blocks.
The example below is a code block that contains a single statement:
{
Code blocks usually contain multiple statements. The example below is a code block that contain multiple statements:
{
int x = 10;
int y = 20;
System.out.println(x + y);
}
A code block enclosing multiple statements
In the code example above, the code block is the section of code between the opening curly brace { and the closing curly brace }. In the
above code block is used to group the int x = 10;, int y = 20;, and System.out.println(x + y); statements. When the code block is executed,
the statements are run from top to bottom.
Logic
• Line 1: We declare a class named MyClass.
• Line 3: We declare a static variable x of type integer. The static keyword is used to mark a variable as a static variable.
• Line 4: We declare a static code block. Here, the x variable is initialized to 10.
• Line 10: The main() method is declared.
• Line 10: The println() statement is used to print the value of x to the console.
When the above code is compiled and run, it will produce the following output:
x -> 10
The output of the static block code example
As you can see from the output, the value of x is 10. This is because the static code block is executed only once when the class is first
loaded.
Creating methods
Code blocks can also be used to create methods in Java. A method is a self-contained section of code that performs a specific task. When
you create a method, you give it a name and specify the code block that contains the statements that the method will execute.
Code example
public static void printSum(int x, int y)
{
// this is the method's code block
// it contains the statements that the method will execute
System.out.println(x + y);
}
A method in Java
• The printSum() method has a code block that contains a single statement.
• This statement prints out the sum of the variables x and y.
Calling a method
You can call a method from another method, or from the main() method. When you call a method, the code in the method's code block is
executed.
class Main
{
public static void printSum(int x, int y)
{
// this is the method's code block
// it contains the statements that the method will execute
System.out.println(x + y);
}
public static void main(String[] args)
{
// this is the main method
Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators, The Java Keywords).
Java programs are the collection of whitespace, identifiers, literals, comments and separators. Lexical issues are very common in
programming, which is used to analysis, operate and implement the program in a sequential order.
Computer languages, like human languages, have a lexical structure. A source code of a Java program consists of tokens. Tokens are
atomic code elements. In Java we have comments, identifiers, literals, operators, separators, and keywords.
Java programs are composed of characters from the Unicode character set.The atomic elements of Java programs is a collection of
whitespace, identifiers, literals, comments, operators, separators, and keywords.
Whitespace
Java is a free-form language. This means that you do not need to follow any special indentation rules. For instance, the Example program
could have been written all on one line or in any other strange way users like typing it, as long as there was at least one whitespace
character between each token that was not already delineated by an operator or separator. In Java, whitespace is a space, tab, or newline.
For example, there is no format to be followed to write a Java program. A program can be written even in a single line or any number of
lines can be used, whatever the user wishes. By default, single whitespace is required between each character.
White space in Java is used to separate tokens in the source file. It is also used to improve readability of the source code.
int i = 0;
White spaces are required in some places. For example between the int keyword and the variable name. In other places, white spaces are
forbidden. They cannot be present in variable identifiers or language keywords.
int a=1;
int b = 2;
int c = 3;
Identifiers
A name given to all the components of Java is known as identifiers An identifier is referred as any descriptive sequence of uppercase,
lowercase letters, underscore or a dollar sign character. Identifiers are used for specifying the class name, method name and variable name.
Since Java is case-sensitive language any letter of a word will be different from another word (VALUE is a different identifier than Value,
The dollar-sign character is not intended for general use.). Some examples of valid identifiers are AvgTEmp, Count, a4, $test, a_b and
invalid identifiers are 2Count, high-temp, Not/ok.
These are valid Java identifiers.
String name23;
int _col;
short car_age;
Example:
class Test
{
public static void main(String[] args)
{
}
}
Test, main are identifiers
Rules of identifiers
Identifiers are case sensitive. This means that Name, name, or NAME refer to three different variables. Identifiers also cannot match
language keywords.
There are also conventions related to naming of identifiers. The names should be descriptive. We should not use cryptic names to
identifiers. If the name consists of multiple words, each subsequent word is capitalized.
The following program demonstrates that the variable names are case sensitive. Event though the language permits this, it is not a
recommended practice to do.
Name and name are two different identifiers. In Visual Basic, this would not be possible. In this language, variable names are not case
sensitive.
$ javac CaseSensitiveIdentifiers.java
$ java CaseSensitiveIdentifiers
Output: GC
CKP
Literals
The data or constant value written by a programmer in the program is known as literals.
Programming needs to be optimized for efficiency, faster outputs, and memory. Variables are key in programming that stores data at a
particular memory location. While executing a Java program, it stores values in containers called variables, a basic storage unit. To enhance
the program‘s readability, one needs to follow particular conventions while naming variables and assigning values. A source code
representing a fixed value is called ‗literal‘.
Literals in Java are defined directly in the code without any kind of computation. Any primitive type variables are assigned using literals.
Java has a generic, class-based, reflective, imperative, multi-paradigm, and is an object-oriented programming language.
Literals in java is represented only for primitive data types like boolean, string, character, or numeric data. The literals in java are a form of
data type covering the fixed values temporarily assigned fixed values as well.
A constant value in Java is created by using a literal representation of it. For example, here are some literals:
Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character constant, and the last is a string. A
literal can be used anywhere a value of its type is allowed.
A literal is a textual representation of a particular value of a type. Literal types include boolean, integer, floating point, string, null, or
character. Technically, a literal will be assigned a value at compile time, while a variable will be assigned at runtime.
The various types of literals in Java are particularly helpful for implementation in the code since it eliminates the need to add labels and
declare constants on the same line.
Types of literals
1. Integral Literals
2. Floating-point Literals
3. Char Literals
4. String Literals
5. Boolean Literals
6. Null Literals
Character Literals
class Char_Lit
{
public static void main(String[] args)
{
char ch = 'a'; // single character literal within a single quote
char b = 0789; // It is an Integer literal with an octal form
char c = '\u0061'; // Unicode representation
System.out.println(ch);
System.out.println(b);
System.out.println(c);
System.out.println("\" is a symbol"); // Escape character literal
}
}
String Literals
String s = ―Hello‖;
class StringLiterals
{
public static void main(String[] args)
{
String myString = "I am a string literal";
System.out.println("String Literals? \n" + myString);
Boolean Literals
boolean b = true;
boolean d = false
Ex: class JavaBooleanLiterals
{
public static void main(String[] args)
{
boolean isTrue = true;
boolean isFalse =false;
System.out.println("The boolean value of isTrue: " + isTrue);
System.out.println("The boolean value of isFalse: " + isFalse);
}
}
Comments
As mentioned, there are three types of comments defined by Java like Single-line, multiline and another type is called a documentation
comment. This type of comment is used to produce an HTML file that documents your program. The documentation comment begins with
a /** and ends with a */.
Separators
In Java, there are a few characters that are used as separators. The most commonly used separator in Java is the semicolon. As you have
seen, it is used to terminate statements. The separators are shown in the following table:
Tokens
It is a smallest unit/part in the all the programming language
1. Keywords
2. Identifiers
3. Literal or values
Keywords
• Keywords is a predefine word which is understandable by a compiler and which having a fixed meaning.
• It is also called as reserve words.
• In Java we have 50 + keywords Example: class, public, static, void, etc...
Rules
• Keywords should be written in lower case.
However, knowing the data types and using them appropriately allows developers to optimize their code because each data type has
specific resource requirements. Also, if you specify one data type and try to store a different type, such as by mistake, you won‘t be able to
compile the code. Thus, with statically typed languages, you can detect errors even before any testing.
Java has two data types: primitive and reference (also known as non-primitive). In this tutorial, you will use variables to store and use
information in a Java program to learn about some of the commonly used data types in Java. This is not an exhaustive overview of all data
types, but this guide will help you become familiar with what options are available to you in Java.
The data-types are the most important basis of any programming language. It is the most important concept for every beginner. The data
type is essential to represent the type, nature and set of operations for the value which it stores.
Java data types are the most basic and initial thing you should know before moving towards other concepts of Java. These are very useful in
every aspect of Java, either to create a simple program or to develop any application or software.
Data types incorporate storage categories like integers, floating-point values, strings, characters, etc.
For example, if a variable is of ―int‖ data type, then it can hold only integer values.
The other is dynamically typed language. In this type of language, the data types can change with respect to time and the variables are
checked during run-time. Some dynamically typed languages are Ruby, Python, Erlang, Perl, VB, and PHP.
In Java, data types play an important role in defining the kind of information that can be stored and manipulated. Data type is defined as the
type of value that variable can occupies in a program.
Data types are important factor in all computer programming languages. The task of a programmer is to develop a program by assigning the
valid types of data to the right variables. Data types represent the type, nature, and set of operations for the value which they store. There
are two data types of categories in Java: Primitive and Non-Primitive.
Data types in Java specify how memory stores the values of the variable. Each variable has a data type that decides the value the variable
will hold. Moreover, Primitive Data Types are also used with functions to define their return type.
Primitive Types
Java primitive types are the simplest and most basic data types in Java. It represents raw values such as numbers and characters. The
primitive data types are the building blocks of the program and the primitive data cannot be manipulate and data cannot be further divided.
The most frequently used primitive data types are int (integers), boolean (boolean values), and char (characters), float (floating point).
The default boolean value is False. Moreover, the boolean type‘s size depends on the Java Virtual Machine. Therefore, it fluctuates on
different platforms.
Example-
class BooleanDataTypes
{
public static void main(String args[])
{
boolean var1 = true;
if (var1 == true) //checks if the value is true or false
{
System.out.println("Boolean value is True");
}
else
{
Integer type
An integer type stores an integer number with no fractional or decimal places. Java has four integer types – byte, short, int, and long.
Byte
The byte is the smallest data type among all the integer data types. It is an 8-bit signed two‘s complement integer. It stores whole numbers
ranging from -128 to 127.
Syntax: byte byteVariable;
Short
Short is a 16-bit signed two‘s complement integer. It stores whole numbers with values ranging from -32768 to 32767. Its default value is 0.
Syntax: short shortVariable;
Int
Long
long is a 64-bit signed two‘s complement integer that stores values ranging from -9223372036854775808(-2^63) to
9223372036854775807(2^63 -1). It is used when we need a range of values more than those provided by int. Its default value is 0L. This
data type ends with ‗L‘ or ‗l‘.
Syntax: long longVariable;
Example:
class IntegerDataTypes
{
public static void main(String args[])
{
int a = 10;
short s = 2;
byte b = 6;
long l = 125362133223l;
System.out.println("The integer variable is " + a + '\n');
System.out.println("The short variable is " + s + '\n');
System.out.println("The byte variable is " + b + '\n');
System.out.println("The long variable is " + l);
}
}
Float type
Floating-point is used for expressions involving fractional precision. floating-point data type that stores the values, including their decimal
precision. It is not used for precise data such as currency or research data. It has two types: float and double.
A Float value: is a single-precision 32-bit or 4 bytes IEEE 754 floating-point can have a 7-digit decimal precision ends with an ‗f‘ or ‗F‘
default value = 0.0f stores fractional numbers ranging from 3.4e-038 to 3.4e+038
Syntax: float floatVariable;
Double
The double data type is similar to float. The difference between the two is that is double twice the float in the case of decimal precision. It is
used for decimal values just like float and should not be used for precise values.
A double value: is a double-precision 64-bit or 8 bytes IEEE 754 floating-point can have a 15-digit decimal precision default value = 0.0d
stores fractional numbers ranging from 1.7e-308 to 1.7e+308
Syntax: double doubleVariable;
Example:
class FloatDataTypes
{
public static void main(String args[])
{
float f = 65.20298f;
double d = 876.765d;
System.out.println("The float variable is " + f);
System.out.println("The double variable is " + d);
}
}
Array
Array is non primitive data type that holds elements of the same type. Array is an object in Java, and the array name (used for declaration)
is a reference value that carries the base address of the continuous location of elements of an array.
Example:
int Array_Name = new int[7];
array_reference_variable
String
The String data type stores a sequence or array of characters. A string is a non-primitive data type, but it is predefined in Java. String literals
are enclosed in double quotes.
class Cs
{
public static void main(String[] args)
{
// create strings
String S1 = "Java String Data type";
// print strings
System.out.println(S1);
}
}
Class
A class is a user-defined data type from which objects are created. It describes the set of properties or methods common to all objects of the
same type. It contains fields and methods that represent the behaviour of an object. A class gets invoked by the creation of the respective
object.
Class acts as a blueprint and a template.
Example: code=class
Example:
interface printable
{
void print();
}
class A1 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A1 obj = new A1();
obj.print();
}
}
Enum
An enum, similar to a class, has attributes and methods. However, unlike classes, enum constants are public, static, and final (unchangeable
– cannot be overridden). Developers cannot use an enum to create objects, and it cannot extend other classes. But, the enum can implement
interfaces.
Java enum, also called Java enumeration type, is a type whose fields consist of a fixed set of constants. The purpose of an enum is to
enforce compile-time type safety. The enum keyword is one of the reserved keywords in Java. The enums are a special type of class that
always extends java.lang.Enum.
In Java, we define enums inside and outside of a class. In Java, an enum is defined as a class type, so we do not need to instantiate the enum
using new; it will contain the same capabilities as other classes.
In the below example, we are defining the enum datatype inside the class as follows: We are creating the class name as enum_class as
follows:
class enum_class
{
enum Level
{
LOWER,
MEDIUM,
HIGHER
}
public static void main(String[] args)
{
Level mv = Level.MEDIUM;
System.out.println (mv);
}
}
Defining the enum datatype outside of the class as follows. We are creating the class name as enum_class as follows.
enum Color
{
GREEN,
BLACK,
BLUE;
}
class enum_class
{
public static void main(String[] args)
{
Color col = Color.BLUE;
System.out.println (col);
}
}
Variable
Variable is a name given to memory location i.e to store the specific format of data in the system. It's a container or block of memory
which is used to store the data. It is defined as the name given or assigned to allocate the data inside the computer memory.
Characteristics of variable
• Variable is a named block of memory
• By using a name user can store the data and can fetch the data
• User cannot store multiple values in single variable name.
Variable declaration
Syntax : datatype variablename ;
Ex: int a;
Variable initialization
Syntax : variablename=value/data ;
Ex: a=20;
Variable is a name given to a memory location The Variable is a block of memory that is typically used to store information. All the
variables must be declared before use in the Java code. During the program execution, the value stored in the variable can be changed.
Variables are just the name of the reserved memory location, and all the operations done on the variables will definitely effects that
memory location.
There are three types of variables in java: local, instance and static. There are two types of data types in java: primitive and non-primitive.
int data=50;//Here data is variable
Types of Variables
Java Programming language defines three types of variables.
1.Instance variables
2.Static Variables
3.Local Variables
Instance variable: These variables are declared within a class but outside any method, constructor, or block of code. They are associated
with individual instances (objects) of the class. Each instance of the class has its own copy of the instance variables. Instance variables are
initialized to their default values if not explicitly assigned.
Static variable: These variables are declared with the static keyword within a class but outside any method, constructor, or block of code.
They are associated with the class itself rather than with instances of the class. Static variables are shared among all instances of the class,
and changes to the variable will be reflected in all instances. Static variables are initialized to their default values if not explicitly assigned.
Ex:class Employee
{
// static variable salary
public static double salary;
public static String name = "H";
}
class StaticVariableExample
{
public static void main (String[]args)
{
// accessing static variable without object
Employee.salary = 75000;
System.out.println (Employee.name + "'s average salary:" + Employee.salary);
}
}
Output: H average salary:75000.0
Primitive variable
A variable which is created by using primitive data type.
}
Demo d1;
class Student
{
}
Student s1;
class Employee
{
}
Employee e1;
•In java user can create any number of non-primitive data type.
Reinitialization
The process of modifying existing data inside the variable is known as reinitialization.
import java.util.Scanner;
class Program
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Write text and enter ");
String text = scanner.nextLine();
System.out.println("You wrote " + text);
}
}
Write text and enter
text
You wrote text
Other input types, such as integers, doubles, and booleans are also read as text. However, they need to be converted to the target variable's
type with the help of syntax provided by Java.
Reading Integers
The Integer.valueOf command converts a string to an integer. It takes the string containing the value to be converted as a parameter.
String valueAsString = "42";
int value = Integer.valueOf(valueAsString);
System.out.println(value);
Output: 42
import java.util.Scanner;
class Program
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Write a value ");
int value = Integer.valueOf(scanner.nextLine());
System.out.println("You wrote " + value);
}
}
Sample output
Write a value
42
You wrote 42
Introducing Type Inference with Local Variables: Local Variable Type Inference
Java 10 introduced a noticeable feature: the Local variable type inference. This allows us to declare local variables without specifying the
type using the varkeyword, the compiler automatically infers its type. This reduces the complex boilerplate declarations and makes the code
look clean.
However, we cannot declare variables everywhere with the var keyword. There are some restrictions, which are given below.
1. Class level
When we say ‗local‘ variable type inference, we can use it strictly in a method's local context. We cannot declare a variable inside a class
(static or instance) using the varkeyword. The compiler throws a compilation error if trying to declare it inside a class.
class Example
{
int rollNumber;
var name; // Compiler Error! - Cannot resolve symbol 'var'
}
Arrays
Arrays in Java store multiple values of the same type in a single variable. They are objects that can hold a fixed number of elements, and
each element has an index used to access it. Arrays enable developers to manipulate data efficiently and perform operations like sorting,
searching, insertion, and deletion quickly and easily.
• In Java array is a predefined class.
• It is a multiple block of memory which is used to store the multiple data.
The array is a referenced data type used to create fixed numbers of multiple variables of the same type to store multiple values of the same
type in continuous memory locations with a single variable name.
Note: Like other data types array is not a keyword rather it is a concept. It creates continuous memory locations using other primitive or
reference types.
Array Limitation: Its size is fixed, which means user cannot increase or decrease its size after its creation.
Features of Array
1. Arrays are objects
2. They can even hold the reference variables of other objects
3. They are created during runtime
4. They are dynamic, created on the heap
5. The Array length is fixed.
An array can be either primitive or reference type. It allocates memory in heap area. Index of array starts from zero to size-1.
Advantages of array:-
1) Length of the code will be decreased
2) User can access the element present in the any location.
3) Readability of the code will be increased
Ex: public static int[] intArr; //Here, int is primitive data type
public static Employee[] empArr; //Employee is a class type or user can say reference type.
Initialization of Array
new operator is used to initialize an array.
Example : int[ ] arr = new int[10]; //10 is the size of array.
or
int[ ] arr = {10,20,30,40,50};
Ex:-printing the array elements by using enhanced for loop called: for-each loop
class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
for (int a1:a)
{
System.out.println(a1);
}
}
}
Characteristics of array
• The size of arrays fixed
• Array is homogeneous data collection
• Arrays index based, the index number is always start from zero
• Duplicates are allowed in arrays
• By using array name, index no we can store the data we can fetch the data
Ex: Here is a complete, executable java code demonstrating the declaration, instantiation, and initialization of an array in java.
class ArrayExample
{
public static void main(String[] args)
{
// Declare an array variable
int[] numbers;
User can create an array of non-primitive data types in java, just the same way as you create an array for primitive data types. Consider the
following example for better understanding.
class Coding
{
private int id;
private String name;
public Coding(int id, String name) //Constructor i.e parametrized constructor
{
this.id = id;
this.name = name;
}
By Using Literals
Method 1: Initialization of array elements at the time of creating array object. It is the most commonly used syntax and can only be used
when declaring a variable of array type.
Syntax: int[] factors= { 1, 2, 3, 4, 6, 12, 24 };
Implementation:
The above statement creates an array of int data types containing 7 elements. Here, we:
• Created an array object without using new keyword.
• Didn‘t specify the type of the array.
• Didn‘t explicitly specify the length of the array object.
Ex:// Java Program to Illustrate Array Literals by Initialization of array elements at the time of creating array object
import java.io.*;
class Cs
{
public static void main(String[] args)
{
// Initializing array elements at the time of
// creating an array object
int[] factors = { 1, 2, 3, 4, 6, 12, 24 };
// Iterating using for each loop
for (int i : factors)
// Print the elements
System.out.print(i + " ");
}
}
Output 1 2 3 4 6 12 24
Method 2: We have another syntax that allows us to use anonymous arrays. Anonymous arrays are arrays that are not assigned to any
variables and hence, they don‘t have names).
Implementation:
The above statement call a method computeVolume with an anonymous array. Here, we:
• Didn‘t store the array in any variable.
• Used new keyword for creating an array object.
• Explicitly specified the type of array.
Example
// Java Program to Illustrate Array Literals Using anonymous arrays
// Importing required classes
import java.io.*;
class Is
{
public static double computeVolume(int[] dimensions)
{
int l = dimensions[0];
int b = dimensions[1];
int h = dimensions[2];
// returning the volume
return (l * b * h);
}
public static void main(String[] args)
{
// Passing an array object directly to a method
// without storing it in a variable
double volume= computeVolume(new int[] { 3, 4, 5 });
Operators:
Java operators are the predefined symbols that are used to perform specific task or operations on variables or operands. It also helps to
manipulate the values of the operands. .
Ex:10+20
Operands:
The data are value between the operators is known as operands.
Expression:
The combination of operator and operand is known as expression.
Types of Operators
1. Arithmetic operators
2. Assignment operators
3. Comparison/Relational operators
4. Logical operators
5. Ternary operators
6. Unary operators
7. Bit wise operator
8. Shift operator
1. Arithmetic operators
It is a operator which is used to perform Arithmetic operations.
Symbols:[+,-,*,/,%]
Ex: classDemo2
{
public static void main(String[]args)
{
2. Assignment operators
It is a shortened operators used to modify the existing data in variable.
Symbols:[=,+=,-=,*=,/=,%=]
Ex:
int a=20;
a += 10;//a=a+10
a - = 15;//a=a-15
a * = 12;//a=a*12
a/=14;//a=a/14
a%=11;//a=a%11
4. Logical operators:
The operator which is used to compare the two condition, the return type of this operator is also Boolean. Ex :[&&,||,!]
a) &&[and]
This operator is used to compare the two condition if both the condition are true then it will return Boolean true otherwise it will return
false.
Truth Table
Condition ReturnValue
False&&True False
False&&False False
True&&True True
If both conditions are satisfied then only it will return True otherwise False
b)|| [or]
This operator is used to compare the two condition if both the condition are false then it will return Boolean false otherwise it will return
true
Truth Table
Condition Return Value
True||False True
False||True True
False||False False
True||True True
If one conditions are satisfied then only it will return True otherwise False
classDemo2
{
public static void main(String[]args)
{
inta=10,b=20,c=10;
System.out.println(true&&false);
System.out.println(true||false);
System.out.println(a>b&&a==c);
System.out.println(b<c || a!=b) ;
System.out.println(a!=c||b==c);
}
}
Chethan Raj C, HoD, Dept of CSE Page 67
Object Oriented Programming using JAVA
c) ![not]
This operator is used to reverse the Boolean output.
Ex:
System.out.println(!true);//false
System.out.println(!false);//true
Unary operator
The operator which will have only one operands is known as unary operator.
Types of unary operator
1. Increment
2. Decrement
6. Ternary operators
A operator which will have a three operands is known as ternary operator
Syntax:Condition?Op2:Op3;
•The return type of this operator is depended upon the data type of operands.
Operator Precedence
In real life when we solve an expression containing multiple operators we follow some rules. For example in an expression 2+3*4, we do
the multiplication first before addition because the multiplication operator has higher precedence than addition operator. The same applies
in java as well.
In java, operator precedence is a rule that tells us the precedence of different operators. Operators with higher precedence are evaluated
before operators with lower precedence. For example in expression a+b*c, the operator * will be evaluated before + operator, because
operator * has higher precedence than + operator.
Table bellow shows the precedence of operators in decreasing order, the operators appearing first in table have higher precedence than
operators appearing later. Operators appearing in same row of table have equal precedence. When operators of equal precedence appears in
the same expression, a rule governs the evaluation order which says that all binary operators except for the assignment operator are
Object Oriented Programming using JAVA
evaluated from left to right while assignment operator is evaluated from right to left. For example in expression 2+3-4, 2 and 3 is added first
then 4 is subtracted from it. Consider a and b as two operands for the examples given in below table.
Logical OR || a||b
Ternary ?: a = a>2 ? a : b
Using Parenthesis
What changes the precedence of the operators in Java : Parentheses "()" are used to alter the order of evaluation. For example in an
expression a+b*c, if you want the addition operation to take place first, then rewrite the expression as (a+b)*c.
result = 5 + 4 / 2 + 6;
System.out.println("5 + 4 / 2 + 6 = " +result);
result = 3 + 6 / 2 * 3 - 1 + 2;
System.out.println("3 + 6 / 2 * 3 - 1 + 2 = " +result);
result = 6 / 2 * 3 * 2 / 3;
Object Oriented Programming using JAVA
System.out.println("6 / 2 * 3 * 2 / 3 = " +result);
int x = 2;
result = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2;
System.out.println("result = " +result);
}
}
Consider the expression x++ + x++ * --x / x++ - --x + 3 >> 1 | 2 is evaluated step by step.
* and / have higher preference than other, * evaluated first as it comes in left
2 + 9 / 3 - 3 + 3 >> 1 | 2
Output
2
1. Nested parentheses in an expression are evaluated from the innermost parentheses to the outermost parenthesis.
2. If evaluation of the left-hand operand of a binary operator does not complete properly, no part of the right-hand operand will be
evaluated.
3. Arguments in a method are evaluated from left to right.
Characteristics of operators
1. Every operator will return data or value.
2. Presidency
3. Associativity
Object Oriented Programming using JAVA
1. Every operator will returns some data or value
Ex:10+20->30
50*2->100
2. Precedence[Priority]
When the expression having more than one operator then precedence comes into picture.
Ex:10+2*3
3. Associativity
• Direction of order of execution.
• When you have the same priority then associativity comes into picture.
Ex:10+20+30
20+10-5
5–2+5
Module 01 Questions