JAVA UNIT-1 Notes
JAVA UNIT-1 Notes
APRIL 1, 2021
MARRI LAXMAN REDDY INSTITUTE OF ENGINEERING AND TECHNOLOGY
DUNDIGAL, HYDERABAD
R20 B. TECH ECE II YEAR
Java Programming
Course Objectives:
Course Outcomes:
UNIT - I:
Object Oriented Thinking and Java Basics: Need for OOP Paradigm, Summary of OOP Concepts,
Coping with Complexity, Abstraction Mechanisms, A Way of Viewing World – Agents, Responsibility,
Messages, Methods, History of Java, Java Buzzwords, Data Types, Variables, Scope and Life Time of
Variables, Arrays, Operators, Expressions, Control Statements, Type Conversion and Casting, Simple
Java Program, Concepts of Classes, Objects, Constructors, Methods, Access Control, This Keyword,
Garbage Collection, Overloading Methods and Constructors, Method Binding, Inheritance, Overriding
and Exceptions, Parameter Passing, Recursion, Nested and Inner Classes, Exploring String Class.
UNIT - II:
Inheritance, Packages and Interfaces: Hierarchical Abstractions, Base Class Object, Subclass,
Subtype, Substitutability, Forms of Inheritance- Specialization, Specification, Construction, Extension,
Limitation, Combination, Benefits of Inheritance, Costs of Inheritance. Member Access Rules, Super
Uses, Using Final with Inheritance, Polymorphism- Method Overriding, Abstract Classes, The Object
Class.
Defining, Creating and Accessing a Package, Understanding Classpath, Importing Packages,
Differences between Classes and Interfaces, Defining an Interface, Implementing Interface, Applying
Interfaces, Variables in Interface and Extending Interfaces, Exploring Java.IO.
UNIT - III:
Exception Handling and Multithreading: Concepts of Exception Handling, Benefits of Exception
Handling, Termination or Resumptive Models, Exception Hierarchy, Usage of Try, Catch, Throw,
Throws and Finally, Built in Exceptions, Creating Own Exception Sub Classes.
String Handling, Exploring Java.Util, Differences between Multi-Threading and Multitasking, Thread Life
Cycle, Creating Threads, Thread Priorities, Synchronizing Threads, Interthread Communication,
Thread Groups, Daemon Threads.
Enumerations, Autoboxing, Annotations, Generics.
UNIT - IV:
Event Handling: Events, Event Sources, Event Classes, Event Listeners, Delegation Event Model,
Handling Mouse and Keyboard Events, Adapter Classes.
R18 B.TECH ECE III YEAR
The AWT Class Hierarchy, User Interface Components- Labels, Button, Canvas, Scrollbars, Text
Components, Check Box, Check Box Groups, Choices, Lists Panels – Scrollpane, Dialogs, Menubar,
Graphics, Layout Manager – Layout Manager Types – Border, Grid, Flow, Card and Grid Bag.
UNIT - V:
Applets: Concepts f Applets, Differences between Applets and Applications, Life Cycle of an Applet,
Types of Applets, Creating Applets, Passing Parameters to Applets.
Swing: Introduction, Limitations of AWT, MVC Architecture, Components, Containers, Exploring
Swing- Japplet, Jframe and Jcomponent, Icons and Labels, Text Fields, Buttons – The Jbutton Class,
Check Boxes, Radio Buttons, Combo Boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.
TEXT BOOKS:
REFERENCES:
1. An Introduction to Programming and OO Design using Java, J. Nino and F.A. Hosch, John
Wiley & Sons.
2. An Introduction to OOP, Third Edition, T. Budd, Pearson Education.
3. Introduction to Java Programming, Y. Daniel Liang, Pearson Education.
4. An Introduction to Java Programming and Object-Oriented Application Development, R.A.
Johnson- Thomson.
5. Core Java 2, Vol 1, Fundamentals, Cay. S. Horstmann and Gary Cornell, Eighth Edition,
Pearson Education.
6. Core Java 2, Vol 2, Advanced Features, Cay. S. Horstmann and Gary Cornell, eighth Edition,
Pearson Education
NEED FOR OOP PARADIGM:
Object-oriented programming (OOP) is a programming paradigm based upon objects (having both
data and methods) that aims to incorporate the advantages of modularity and reusability. Objects,
which are usually instances of classes, are used to interact with one another to design applications
and computer programs.
The important features of object–oriented programming are −
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
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's data
or code. The only necessary thing is the type of message accepted and the type of response returned
by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors
like wagging the tail, barking, eating, etc.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince
the customer differently, to draw something, for example, shape, triangle, rectangle, etc.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Hiding internal details and showing functionality is known as abstraction. For example phone call,
we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Procedure oriented approach:
The Languages like C, Fortran, Pascal, etc., are called procedure oriented programming
languages since in these languages, a programmer uses procedures or functions to perform a
task. When the programmer wants to write a program, he will first divide the task into several
subtasks, each of which expressed as a function. So, C program generally contains several
functions which are called and controlled from main() function. This approach is called
procedure oriented approach.
Principles of OOP:
The key ideas of the object oriented approach are:
Class / Objects
Abstraction
Encapsulation
Inheritance
Polymorphism
Class / Objects
Entire OOP methodology has been derived from a single root concept, called 'object'.
An object is anything that really exists in the world and can be distinguished from others.
This definition specifies that everything in this world is an object. For example, a table, a
ball, a car, a dog, a person, etc., everything will come under objects.
Every object has properties and can perform certain actions. For example, let us take a
person whose name is 'Raju'. Raju is an object because he exists physically. He has properties
like name, age, gender, etc. These properties can be represented by variables in our
programming.
String name;
int age;
char gender;
Similarly, Raju can perform some actions like talking, walking, eating and sleeping.
We may not write code for such actions in programming. But, we can consider calculations
and processing of data as actions. These actions are performed by methods (functions), So an
object contains variables and methods.
Abstraction
There may be a lot of data, a class contains and the user does not need the entire data.
The user requires only some part of the available data. In this case, we can hide the
unnecessary data from the user and expose only that data that is of interest to the user. This is
called abstraction.
A bank clerk should see the customer details like account number, name and balance
amount in the account. He should not be entitled to see the sensitive data like the staff
salaries, profit or loss of the bank amount paid by the bank and loans amount to be recovered
etc,. So such data can abstract from the clerk's view. Whereas the bank manager is interested
to know this data, it will be provided to the manager.
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as a single unit. In encapsulation, the variables of a
class will be hidden from other classes, and can be accessed only through the methods of
their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
Inheritance
It creates new classes from existing classes, so that the new classes will acquire all the
features of the existing classes is called Inheritance. A good example for Inheritance in nature
is parents producing the children and children inheriting the qualities of the parents.
There are three advantages inheritance. First, we can create more useful classes
needed by the application (software). Next, the process of creating the new classes is very
easy, since they are built upon already existing classes. The last, but very important
advantage is managing the code becomes easy, since the programmer creates several classes
in a hierarchical manner, and segregates the code into several modules.
Polymorphism
The word polymorphism came from two Greek words 'poly' meaning 'many' and
'morphos' meaning 'forms'. Thus, polymorphism represents the· ability to assume several
different forms. In programming, we can use a single variable to refer to objects of different
types and thus using that variable we can call the methods of the different objects. Thus
method call can perform different tasks depending on the type of object.
Polymorphism provides flexibility in writing programs in such a way that the
programmer uses same method call to perform different operations depending on the
requirement.
Application of OOP:
The promising areas includes the followings,
1. Real Time Systems Design
2. Simulation and Modeling System
3. Object Oriented Database
4. Object Oriented Distributed Database
5. Client-Server System
6. Hypertext, Hypermedia
7. Neural Networking and Parallel Programming
8. Decision Support and Office Automation Systems
9. CIM/CAD/CAM Systems
10. AI and Expert Systems
When programs are larger then complex is more programmers found it difficult to remember all the
information they needed to know in order to develop or debug their software.
When projects become larger, a task that can be solved by a programmer in 2 months can’t be
accomplished by 2 programmers working for one month. The reason for this non-linear behavior is
complexity. The inter connections between the software components is complicated. The OOP
designers illustrated this with a memorable phrase “The bearing of a child takes nine months, no
matter how many women are assigned to the task”
JAVA PROGRAMMING UNIT-1
ABSTRACTION MECHANISM
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
In this example, Shape is the abstract class, and its implementation is provided by the Rectangle
and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an
object of the implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory
method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
Page 1
JAVA PROGRAMMING UNIT-1
File: TestAbstraction1.java
Page 2
JAVA PROGRAMMING UNIT-1
Responsibility
• In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of
a source of command objects and a series of processing objects..
• Each processing object contains logic that defines the types of command objects that it can
handle; the rest are passed to the next processing object in the chain. A mechanism also
exists for adding new processing objects to the end of this chain.
Primary motivation is the need for a platform-independent (that is, architecture- neutral)
language that could be used to create software to be embedded in various consumer
electronic devices, such as microwave ovens and remote controls.
• Objects with clear responsibilities
• Each class should have a clear responsibility.
• If you can't state the purpose of a class in a single, clear sentence, then perhaps your class
structure needs some thought.
• In object-oriented programming, the single responsibility principle states that every
class should have a single responsibility, and that responsibility should be entirely
encapsulated by the class. All its services should be narrowly aligned with that
responsibility.
Messages
• Message implements the Part interface. Message contains a set of attributes and a
"content".
• Message objects are obtained either from a Folder or by constructing a new Message
object of the appropriate subclass. Messages that have been received are normally
retrieved from a folder named "INBOX".
• A Message object obtained from a folder is just a lightweight reference to the actual
message. The Message is 'lazily' filled up (on demand) when each item is requested from
the message.
• Note that certain folder implementations may return Message objects that are pre-filled
with certain user-specified items. To send a message, an appropriate subclass of Message
(e.g., Mime Message) is instantiated, the attributes and content are filled in, and the
message is sent using the Transport. Send method.
Page 3
JAVA PROGRAMMING UNIT-1
• We all like to use programs that let us know what's going on. Programs that keep us
informed often do so by displaying status and error messages.
• These messages need to be translated so they can be understood by end users around the
world.
• The Section discusses translatable text messages. Usually, you're done after you move a
message String into a Resource Bundle.
• If you've embedded variable data in a message, you'll have to take some extra steps to
prepare it for translation.
Methods
• The only required elements of a method declaration are the method's return type, name,
a pair of parentheses, (), and a body between braces, {}.
• Two of the components of a method declaration comprise the method signature—the
method's name and the parameter types.
• More generally, method declarations have six components, in order:
• Modifiers—such as public, private, and others you will learn about later.
The return type—the data type of the value returned by the method, or void if the method
does not return a value.
• The method name—the rules for field names apply to method names as well, but the
convention is a little different.
• The parameter list in parenthesis—a comma-delimited list of input parameters, preceded
by their data types, enclosed by parentheses, (). If there are no parameters, you must use
empty parentheses.
• The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.
Page 4
JAVA PROGRAMMING UNIT-1
History of Java:
Before starting to learn Java, let us plunge into its history and see how the language
originated. In 1990, Sun Microsystems Inc. (US) was conceived a project to develop software
for consumer electronic devices that could be controlled by a remote. This project was called
Stealth Project but later its name was changed to Green Project.
In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton, and
several others met in Aspen, Colorado to discuss this' project. Mike Sheradin was to focus on
business development; Patrick Naughton was to begin work on the graphics system; and
James Gosling was to identify the proper programming language for the project. Gosling
thought C and C++ could be used to develop the project.
But the problem he faced with them is that they were system dependent languages and
hence could not be used on various processors, which the electronic devices might use. So he
started developing a new language, which was completely system independent. This language
was initially called Oak. Since this name was registered by some other company, later it was
changed to Java.
Why the name Java? James Gosling and his team members were consuming a lot of
tea while developing this language. They felt that they were able to develop a better language
because of the good quality tea they had consumed. So the tea also had its own role in
developing this language and hence, they fixed the name for the language as Java. Thus, the
symbol for Java is tea cup and saucer.
Features of Java:
Simple: Java is a simple programming language. Rather than saying that this is the
feature of Java, we can say that this is the design aim of Java. JavaSoft (the team who
developed Java is called with this name) people maintained the same syntax of C and
C++ in Java, so that a programmer who knows C or C++ will find Java already familiar.
Object-oriented: Java is an object oriented programming language. This means Java
programs use objects and classes. What is an object? An object is anything that really
exists in the world and can be distinguished from others.
Page 5
JAVA PROGRAMMING UNIT-1
Page 6
JAVA PROGRAMMING UNIT-1
First of all, the .java program is converted into a .class file consisting of byte code
instructions by the java compiler. Remember, this java compiler is outside the JVM: Now this
.class file is given to the JVM. In JVM, there is a module (or program) called class loader
sub system, which performs the following functions:
First of all, it loads the .class file into memory.
Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.
If the byte instructions are proper, then it allocates necessary memory to execute the
program.
This memory is divided into 5 parts, called run time data areas, which contain the data and
results while running the program. These areas are as follows:
Method area: Method area is the memory block, which stores the class code, code of
the variables, and code of the methods in the Java program. (Method means functions
written in a class)
Heap: This is the area where objects are created. Whenever JVM loads a class, a
method and a heap area are immediately created in it.
Java Stacks: Method code is stored on Method area. But while running a method, it
needs some more memory to store the data and results. This memory is allotted on Java
stacks.
PC (Program Counter) registers: These are the registers (memory areas), which
contain memory address of the instructions of the methods. If there are 3 methods, 3 PC
registers will be used to track the instructions of the methods.
Native method stacks: Java methods are executed on Java stacks. Similarly, native
methods (for example C/C++ functions) are executed on Native method stacks. To
execute the native methods, generally native method libraries (for example C/C++
header files) are required. These header files are located and connected to JVM by a
program, called Native method interface.
Execution engine contains interpreter and JIT (Just In Time) compiler, which are
responsible for converting the byte code instructions into machine code so that the processor
will execute them. Most of the JVM implementations use both the interpreter and JIT
compiler simultaneously to convert the byte code. This technique is also called adaptive
optimizer. Generally, any language (like C/C++, Fortran, COBOL, etc.) will use either an
interpreter or a compiler to translate the source code into a machine code. But in JVM, we got
interpreter and JIT compiler both working at the same time on byte code to translate it into
machine code.
Java Program Structure:
Documentation Section
Package Statement
Import Statements
Interface Statement
Class Definition
Main Method Class
o Main Method Definition
Page 7
JAVA PROGRAMMING UNIT-1
Program Output:
Hello Java
Comments:
Single line comments: These comments are for marking a SL'1gle line as a comment.
These comments start with double slash symbol / / and after this, whatever is written
till the end of the line is taken as a comment. For example,
// This is single line comment
Page 8
JAVA PROGRAMMING UNIT-1
Multi-line comments: These comments are used for representing several lines as
comments. These comments start with / * and end with * /. In between / * and * /,
whatever is written is treated as a comment. For example,
/* This is Multi line comment,
Line 2 is here
Line 3 is here */
Importing Classes:
In C/C++ compiler to include the header file <stdio.h>. What is a header file? A
header file is a file, which contains the code of functions that will be needed in a program. In
other words, to be able to use any function in a program, we must first include the header file
containing that function's code in our program. For example, <stdio.h> is the header me that
contains functions, like printf (), scanf (), puts (), gets (), etc. So if we want to use any of
these functions, we should include this header file in our C/C++ program.
A similar but a more efficient mechanism, available in case of Java, is that of
importing classes. First, we should decide which classes are 'needed in our program.
Generally, programmers are interested in two things:
Using the classes by creating objects in them.
Using the methods (functions) of the classes.
In Java, methods are available in classes or interfaces. What is an interface? An interface
is similar to a class that contains some methods. Of course, there is a lot of difference
between an interface and a class, which we will discuss later. The main point to be kept in
mind, at this stage, is that a class or an interface contains methods. A group of classes and
interfaces are contained in a package. A package is a kind of directory that contains a group
of related Classes and interfaces and Java has several such packages in its library,
Java library
|
Packages
|
Classes and interfaces
|
Methods
In our first Java program, we are using two classes namely, System and String. These
classes belong to a package called java .lang (here lang represents language). So these two
classes must be imported into our program, as shown below:
import java.lang.System;
import java.lang.String;
Whenever we want to import several classes of the same package, we need not write
several import statements, as shown above; instead, we can write a single statement as:
import java.lang.*;
Here, * means all the classes and interfaces of that package, i.e. java.lang, are
imported made available) into our program. In import statement, the package name that we
have written acts like a reference to the JVM to search for the classes there. JVM will not
copy any code from the classes or packages. On the other hand, when a class name or a
Page 9
JAVA PROGRAMMING UNIT-1
method name is used, JVM goes to the Java library, executes the code there, comes back, and
substitutes the result in that place of the program. Thus, the Java program size will not be
increased.
After importing the classes into the program, the next step is to write a class, Since
Java is purely an object-oriented programming language and we cannot write a Java program
without having at least one class or object. So, it is mandatory that every Java program should
have at least one class in it, How to write a class? We should use class keyword for this
purpose and then write the class name.
class Hello{
statements;
}
A class code starts with a { and ends with a }. We know that a class or an object
contains variables and methods (functions), 'So we can create any number of variables and
methods inside the class. This is our first program, so we will create only one method, i.e.
compulsory, main () method.
The main method is written as follows:
public static void main(String args[ ])
Here args[ ] is the array name and it is of String type. This means that it can store a
group of strings. Remember, this array can also store a group of numbers but in the
form of strings only. The values passed to main( ) method are called arguments. These
arguments are stored into args[ ] array, so the name args[ ] is generally used for it.
If a method is not meant to return any value, then we should write void before that
method's name. void means no value. main() method does not return any value, so void
should be written before that method's name.
static methods are the methods, which can be called and executed without creating the
objects. Since we want to call main()method without using an object, we should
declare main( ) method as static. Then, how is the main( ) method called and executed?
The answer is by using the classname.methodname(). JVM calls main() method
using its class name as Hello.main() at the time of running the program.
JVM is a program written by JavaSoft people (Java development team) and main() is
the method written by us. Since, main() method should be available to the JVM, it
should be declared as public. If we don't declare main() method as public, then. It
doesn't make itself available to JVM and JVM cannot execute it:
So, the main()method should always be written as shown here:
public static void main(String args[ ])
If at all we want to make any changes, we can interchange public and static and write it as
follows:
static public void main(String args[])
Or, we can use a different name for the string type array and write it as:
public static void main(String x[])
Q) When main() method is written without String args[args]:
public static void main ()
Ans: The code will compile but JVM cannot run the code because it cannot
recognize the main () method as the method from where it should start
execution of the Java program. Remember JVM always looks for main () method
with string type array as parameter.
Page 10
JAVA PROGRAMMING UNIT-1
Page 11
JAVA PROGRAMMING UNIT-1
Data types:
Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning different data
types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java −
a) Primitive Data Types
b) Reference/Object Data Types
a) Primitive Data Types
There are eight primitive datatypes supported by Java. Primitive datatypes are
predefined by the language and named by a keyword. Let us now look into the eight
primitive data types in detail.
Float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Page 12
JAVA PROGRAMMING UNIT-1
byte
• Byte data type is an 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
• Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is
four times smaller than an integer.
• Example: byte a = 100, byte b = -50
short
• 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 smaller
than an integer
• Default value is 0.
• Example: short s = 10000, short r = -20000
int
• 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)
• Integer is generally used as the default data type for integral values unless there is a concern
about memory.
• The default value is 0
• Example: int a = 100000, int b = -200000
long
• 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)(2^63 -1)
• This type is used when a wider range than int is needed
• Default value is 0L
• Example: long a = 100000L, long b = -200000L
float
• 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
• Float data type is never used for precise values such as currency
• Example: float f1 = 234.5f
Page 13
JAVA PROGRAMMING UNIT-1
Double
• 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
• Double data type should never be used for precise values such as currency
• Default value is 0.0d
• Example: double d1 = 123.4
Boolean
• boolean data type represents one bit of information
• There are only two possible values: true and false
• This data type is used for simple flags that track true/false conditions
• Default value is false
• Example: boolean one = true
char
• char data type is a single 16-bit Unicode character
• Minimum value is '\u0000' (or 0)
• Maximum value is '\uffff' (or 65,535 inclusive)
• Char data type is used to store any character
• Example: char letterA = 'A'
Page 14
JAVA PROGRAMMING UNIT-1
to access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any
compatible type.
Example: Animal an = new Animal("giraffe");
Variables:
• A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
• Variable is a name of 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 a = 10;
Int data type
a variable
10 value
A variable provides us with named storage that our programs can manipulate. Each
variable in Java has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.
You must declare all variables before they can be used. Following is the basic form
of a variable declaration −
DataType variable [ = value][, variable [ = value] ...] ;
Here DataType is one of Java's datatypes and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java −
Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'
Page 15
JAVA PROGRAMMING UNIT-1
There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
Example 1
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited
to only this method.
class Test {
void pupAge( ) {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
Page 16
JAVA PROGRAMMING UNIT-1
b) Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access
modifiers.
Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned during
the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the
class. However, within static methods (when instance variables are given
accessibility), they sho3333333111uld be called using the fully
qualified name. ObjectReference.VariableName.
Example 1
import java.io.*;
public class Employee {
public String name;
public Employee (String empName) {
name = empName;
}
public void printEmp() {
System.out.println("name : " + name );
}
public static void main(String args[]) {
Employee empOne = new Employee("Sai krishna");
empOne.printEmp();
}
}
This will produce the following result −
Output
name : Sai krishna
c) Class/Static Variables
Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables
never change from their initial value.
Page 17
JAVA PROGRAMMING UNIT-1
Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
Default values are same as instance variables. Static variables can be accessed by
calling with the class name ClassName.VariableName.
Example 1
import java.io.*;
public class Employee {
private static double salary;
public static void main(String args[]) {
salary = 1000;
System.out.println("average salary:" + salary);
}
}
This will produce the following result −
average salary:1000
Arrays:
Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Page 18
JAVA PROGRAMMING UNIT-1
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
Declaring Single Dimensional Array:
To use an array in a program, you must declare a variable to reference the array, and
you must specify the type of array the variable can reference. Here is the syntax for declaring
an array variable −
Syntax:
dataType[] varName;
or
dataType varName[];
Example:
int a[]; or int[] a;
Page 19
JAVA PROGRAMMING UNIT-1
Two-Dimensional Array:
The declaration and instantiating of an 1-D array is, as follows
Example:
int[][] a=new int[2][3];
Page 20
JAVA PROGRAMMING UNIT-1
Page 21
JAVA PROGRAMMING UNIT-1
Page 22
JAVA PROGRAMMING UNIT-1
Operators:
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Page 23
JAVA PROGRAMMING UNIT-1
Page 24
JAVA PROGRAMMING UNIT-1
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Page 25
JAVA PROGRAMMING UNIT-1
Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true : value if false
Page 26
JAVA PROGRAMMING UNIT-1
Example
public class Test {
instanceof Operator
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). instanceof operator is written as −
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true. Following is an example
Example
public class Test {
Page 27
JAVA PROGRAMMING UNIT-1
}
}
This will produce the following result −
Output
true
Precedence of Java Operators
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Category Operator Associativity
Postfix >() [] . (dot operator) Left toright
Unary >++ - - ! ~ Right to left
Multiplicative >* / Left to right
Additive >+ - Left to right
Shift >>> >>> << Left to right
Relational >> >= < <= Left to right
Equality >== != Left to right
Bitwise AND >& Left to right
Bitwise XOR >^ Left to right
Bitwise OR >| Left to right
Logical AND >&& Left to right
Logical OR >|| Left to right
Conditional ?: Right to left
Assignment >= += -= *= /= %= >>= <<= &= ^= |= Right to left
Page 28
JAVA PROGRAMMING UNIT-1
Identifiers:
Identifiers are the names of variables, methods, classes, packages and interfaces. In the Hello
program, Hello, String, args, main and print are identifiers. There are a few rules and
conventions related to the naming of variables.
The rules are:
1. Java variable names are case sensitive. The variable name money is not the same
as Money or MONEY.
2. Java variable names must start with a letter, or the $ or _ character.
3. After the first character in a Java variable name, the name can also contain numbers
(in addition to letters, the $, and the _ character).
4. Variable names cannot be equal to reserved key words in Java. For instance, the
words int or forare reserved words in Java. Therefore you cannot name your
variables int or for.
Here are a few valid Java variable name examples:
myvar myVar MYVAR _myVar
$myVar myVar1 myVar_1
Java Literals
A literal is a value that is stored into a variable directly in the program. There are 5
types of literals.
a) Integer Literals
b) Float Literals
c) Character Literals
d) String Literals
e) Boolean Literals
a) Integer Literals
class Test {
public static void main(String[] args)
{
int dec = 101; // decimal-form literal
int oct = 0100; // octal-form literal
int hex = 0xFace; // Hexa-decimal form literal
System.out.println(dec); //101
System.out.println(oct); //64
System.out.println(hex); //64206
}
}
Page 29
JAVA PROGRAMMING UNIT-1
b) Float Literals
class Test {
public static void main(String[] args)
{
double d1 = 123.4;
double d2 = 1.234e2; //Same value as d1, but in scientific notation
float f1 = 123.4f;
System.out.println(d1); //123.4
System.out.println(d2); //123.4
System.out.println(f1); //123.4
}
}
c) Character Literals
public class Test {
public static void main(String[] args)
{
char ch1 = 'a';
char ch2 = '\"';
char ch3 = '\n';
char ch4 = '\u0015';
System.out.println(ch1); // a
System.out.println(ch2); // “
System.out.println(ch3); //
System.out.println(ch4); // §
}
}
d) String Literals
String literals represent objects of String class. For example, Hello, Anil
Kumar, AP1201, etc. will come under string literals, which can be directly stored into
a String object.
e) Boolean Literals
Boolean literals represent only two values-true and false, It means we can
store either true or false into a boolean type variable.
Page 30
JAVA PROGRAMMING UNIT-1
double d2 = 66.0;
char ch2 = (char) d2;
System.out.println(ch2); // prints B
}
}
Page 31
JAVA PROGRAMMING UNIT-1
JAVA EXPRESSIONS
A Java expression consists of variables, operators, literals, and method calls. To know more
about method calls, visit Java methods.
For example,
int score;
score = 90; Here, score = 90 is an expression that returns an int
Consider another example,
Double a = 2.2, b = 3.4, result;
result = a + b - 3.4; // here, a + b - 3.4 is an expression
Expression statements
We can convert an expression into a statement by terminating the expression with a ;. These
are known as expression statements. For example,
// expression
number = 10
// statement
number = 10;
CONTROL STATEMENTS
Java compiler executes the java code from top to bottom. The statements are executed
according to the order in which they appear. However, Java provides statements that
can be used to control the flow of java code. Such statements are called control flow
statements.
2. Loop statements
3. Jump statements
Decision-Making statements:
Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the condition result. There are two types of decision-making
statements in java, I.e., If statement and switch statement.
If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the condition result that is a Boolean value, either true or
false. In java, there are four types of if-statements given below.
1. if statement
Page 32
JAVA PROGRAMMING UNIT-1
2. if-else statement
3. else-if statement
4. Nested if-statement
1. if statement:
This is the most basic statement among all control flow statements in java. It
evaluates a Boolean expression and enables the program to enter a block of code
if the expression evaluates to true.
Consider the following example in which we have used the if statement in the java code.
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Page 33
JAVA PROGRAMMING UNIT-1
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
Example:
Output:
Page 34
JAVA PROGRAMMING UNIT-1
LEAP YEAR
Syntax:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Example:
Output:
C grade
Output:
NEGATIVE
Page 36
JAVA PROGRAMMING UNIT-1
Syntax:
1. if(condition){
2. //code to be executed
3. if(condition){
4. //code to be executed
5. }
6. }
Example:
Output:
Page 37
JAVA PROGRAMMING UNIT-1
Loops in Java
In programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true. There are three types of loops in Java.
o while loop
o do-while loop
o for loop
Syntax:
1. while(condition){
2. //code to be executed
3. }
Example:
The Java do-while loop is executed at least once because condition is checked after loop
Page 38
JAVA PROGRAMMING UNIT-1
Syntax:
1. do{
2. //code to be executed
3. }while(condition);
Example:
Ouuput: 1 2 3 4 5 6 7 8 9 10
Example 2:
public class Test {
do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Page 39
JAVA PROGRAMMING UNIT-1
1. 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.
2. 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.
3. Statement: The statement of the loop is executed each time until the second
condition is false.
Syntax:
1. for(initialization;condition;incr/decr){
2. //statement or code to be executed
3. }
Example:
Page 40
JAVA PROGRAMMING UNIT-1
The Java break statement is used to break loop or switch statement. It breaks the
current flow of the program at specified condition. In case of inner loop, it breaks only
inner loop.
We can use Java break statement in all types of loops such as for loop, while
loop and do-while loop.
Syntax:
1. jump-statement;
2. break;
Example:
Output: 1 2 3 4
Page 41
JAVA PROGRAMMING UNIT-1
The Java continue statement is used to continue the loop. It continues the current flow
of the program and skips the remaining code at the specified condition. In case of an
inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop
and do-while loop.
Syntax:
1. jump-statement;
2. continue;
Example:
Output: 1 2 3 4 6 7 8 9 10
Page 42
JAVA PROGRAMMING UNIT-1
Points to remember
o It is used to exit from the method.
o The value passed with return keyword must match with return type of the
method.
Example 1
1. public class ReturnExample1 {
2. int display()
3. {
4. return 10;
5. }
6. public static void main(String[] args) {
7. ReturnExample1 e =new ReturnExample1();
8. System.out.println(e.display());
9. }
10. }
OUTPUT : 10
Example 2:
1. public class ReturnExample2 {
2. void display()
3. {
4. return null;
5. }
6. public static void main(String[] args) {
7. ReturnExample2 e =new ReturnExample2();
8. e.display();
9. }
10. }
OUTPUT: Void methods cannot return a value
Page 43
JAVA PROGRAMMING UNIT-1
Type casting
Convert a value from one data type to another data type is known as type casting.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not
done automatically. Also, the char and Boolean data types are not compatible
with each other. Let's see an example.
WideningTypeCastingExample.java
Page 44
JAVA PROGRAMMING UNIT-1
13. }
14. }
Output
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times.
First, we have converted the double type into long data type after that long data type is
converted into int type.
NarrowingTypeCastingExample.java
Output:
Before conversion: 166.66
After conversion into long type: 166
Page 45
JAVA PROGRAMMING UNIT-1
After conversion into int type: 166
o Install the JDK if you don't have installed it, download the JDK and install it.
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
Page 46
JAVA PROGRAMMING UNIT-1
the JVM, so it doesn't require to create an object to invoke the main method. So
it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o String[] args is used for command line argument. We will learn it later.
Page 47
JAVA PROGRAMMING UNIT-1
JVM. When an object is created, the memory is allocated on 'heap'. After creation of an
object, JVM produces a unique reference number for the object from the memory address of
the object. This reference number is also called hash code number.
To know the hashcode number (or reference) of an object, we can use hashCode() method
object class, as shown here:
Person p = new Person();
System.out.println(p.hashCode());
The object reference, (hash code) internally represents heap memory where instance-
variables are stored. There would be a pointer (memory address) from heap memory to a
special structure located in method area. In method area, a table is available which contains
pointers to static variables and methods.
Page 48
JAVA PROGRAMMING UNIT-1
class Person
{
String name;
int age;
void talk()
{
System.out.println("Hello my name is "+name);
System.out.println("and my age is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p = new Person();
System.out.println(p.hashCode()); // 705927765
}
}
Initializing the instance variables:
It is the duty of the programmer to initialize the instance depending on his
requirements. There are various ways to do this.
First way is to initialize the instance variables of Person class in other class, i.e.,
Demo class. For this purpose, the Demo class can be rewritten like this:
class Demo
{
public static void main(String args[])
{
Person p = new Person();
p.name="Raju";
p.age=22;
System.out.println(p.hashCode()); // 705927765
}
}
Second way is to initialize the instance variables of Person class in the Same class.
For this purpose, the Person class can be rewritten like this:
class Person
{
String name="Raju";
int age=22;
void talk()
{
System.out.println("My Name is "+name);
System.out.println("My Age is "+age);
}
}
Page 49
JAVA PROGRAMMING UNIT-1
class Demo
{
public static void main(String args[])
{
Person p1 = new Person();
System.out.println("p1 hashcode "+p1.hashCode());
p1.talk();
Person p2 = new Person();
System.out.println("p2 hashcode "+p2.hashCode());
p2.talk();
}
}
Output:
p1 hashcode 705927765
My Name is Raju
My Age is 22
p2 hashcode 705934457
My Name is Raju
My Age is 22
But, the problem in this way of initialization is that all the objects are initializing with same
data.
Constructors:
The third possibility of initialization is using constructors. A constructor is similar to a
method is used to initialize the instance variables. The sole purpose of a constructor is to
initialize the instance variables. A constructor has the following characteristics:
The constructor's name and class name should be same. And the constructor's name
should end with a pair of simple braces.
Person()
{
}
A constructor may have or may not have parameters: Parameters are variables to
receive data from outside into the constructor. If a constructor does not have any
parameters, it is called ‘Default constructor’. If a constructor has 1 or more parameters,
it is called ‘parameterized constructor’; For example, we can write a default constructor
as:
Person()
{
}
And a Parameterized constructor with two parameters, as:
Person(String s, int i)
{
}
Page 50
JAVA PROGRAMMING UNIT-1
A constructor does not return any value, not even 'void'. Recollect, if a method does not
return any value, we write 'void' before the method name. That means, the method is
returning ‘void’ which means 'nothing'. But in case of a constructor, we should not even
write 'void' before the constructor.
A constructor is automatically called and executed at the time of creating an object.
While creating an object, if nothing is passed to, the object, the default constructor is
called and executed. If-some values are passed to the object, then the parameterized
constructor is called. For example, if we create the object as:
Person p = new Person(); // Default Constructor
Person p = new Person(Raju, 22); // Parameterized Constructor
A constructor is called and executed only once per object. This means .when we create
an object, the constructor is called. When we create second object, again the constructor
is called second time.
class Person
{
String name;
int age;
Person()
{
name="Raju";
age=22;
}
void talk()
{
System.out.println("Hello my name is "+name);
System.out.println("and my age is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p = new Person(); // Default Constructor
System.out.println("p hashcode "+p.hashCode());
p.talk();
Person p1 = new Person();
System.out.println(p1.hashCode());
p1.talk();
}
}
Output:
p hashcode 705927765
My Name is Raju
My Age is 22
p1 hashcode 705934457
My Name is Raju
My Age is 22
Page 51
JAVA PROGRAMMING UNIT-1
From the output, we can understand that the same data "Raju" and 22 are store in both
objects p1 and p2. p2 object should get p2’s data, not p1’s data. Isn't it? To mitigate the
problem, let us try parameterized constructor, which accepts data from outside and initializes
instance variables with that data.
class Person
{
String name;
int age;
Person()
{
name="Raju";
age=22;
}
Person(String s, int i)
{
name=s;
age=i;
}
void talk()
{
System.out.println("My Name is "+name);
System.out.println("My Age is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p1 = new Person();
System.out.println("p1 hashcode "+p1.hashCode());
p1.talk();
Person p2 = new Person("Sita",23);
System.out.println(p2.hashCode());
p2.talk();
}
}
Output:
p1 hashcode 705927765
My Name is Raju
My Age is 22
p2 hashcode 705934457
My Name is Sita
My Age is 23
Page 52
JAVA PROGRAMMING UNIT-1
Page 53
JAVA PROGRAMMING UNIT-1
double volume()
{
return width * height * depth;
}
}
public class Test
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mybox3 = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
vol = mybox3.volume();
System.out.println(" Volume of mybox3 is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mybox3 is 343.0
Page 54
JAVA PROGRAMMING UNIT-1
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 collec
tion
3) By annonymous 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(){}
Program:
public class TestGarbage1
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected
Methods in Java:
A method represents a group of statements that performs a task. Here 'task' represents
a calculation or processing of data or generating a report etc.
A Method has two types:
Method Header
Method Body
Page 55
JAVA PROGRAMMING UNIT-1
Method Header: It contains method name, method parameters and method return
data type.
returntype methodName(parameters)
Method Body: Method body consists of group of statements which contains logic to
perform the task.
{
Statements;
}
If a method returns some value, then a return statement should be written within the
body of method, as:
return somevalue;
There are two types of methods in java:
a) Instance methods
b) Static methods
a) Instance Methods:
Instance methods are the methods which act on the instance variables of the
class. To call the instance methods, we should use the form:
objectname. methodname ();
Example-1: Write a program to perform addition of two numbers using instance
method without return statement.
class Addition
{
void add(double a,double b)
{
double c=a+b;
System.out.println("Addition is "+c);
}
}
class MethodDemo
{
public static void main(String args[])
{
Addition a1=new Addition();
a1.add(27,35);
}
}
Output:
Addition is 62
Example-2: Write a program to perform addition of two numbers using instance
method with return statement.
class Addition
{
double add(double a,double b)
{
double c=a+b;
return c;
}
Page 56
JAVA PROGRAMMING UNIT-1
}
class MethodDemo
{
public static void main(String args[])
{
Addition a1=new Addition();
double c=a1.add(27,35);
System.out.println("Addition is "+c);
}
}
Output:
Addition is 62
b) Static Methods:
Static methods are the methods which do not act on the instance variables of
the class. static methods are declared as ‘static’. To call the static methods, we need
not create the object. we call a static method, as:
ClassName. methodname ();
Example-1: Write a program to perform addition of two numbers using static method
without return statement.
class Addition
{
static void add(double a,double b)
{
double c=a+b;
System.out.println("Addition is "+c);
}
}
class MethodDemo
{
public static void main(String args[])
{
Addition.add(27,35);
}
}
Output:
Addition is 62
Example-2: Write a program to perform addition of two numbers using static method
with return statement.
class Addition
{
static double add(double a,double b)
{
double c=a+b;
return c;
}
}
class MethodDemo
{
Page 57
JAVA PROGRAMMING UNIT-1
}
}
Output:
Addition is 62
Static Block:
A static block is a block of statements declared as ‘static’.
static {
statements;
}
JVM executes a static block on highest priority basis. This means JVM first goes to
static block even before it looks for the main() method in the program.
Example-1: Write a program to test which one is-executed first by JVM, the static block or
the static method.
class Demo
{
static
{
System.out.println("Static block");
}
public static void main(String args[])
{
System.out.println("Static Method");
}
}
Output:
Static block
Static Method
Example-2: Write a java program without main() method.
class Demo
{
static
{
System.out.println("Static block");
}
}
Output:
Static block
Page 58
JAVA PROGRAMMING UNIT-1
Q: Is it possible to compile and run a Java program without writing main() method?
Ans: Yes, it is possible by using a static block in theJava program.
'this' keyword:
'this' is a keyword that refers to the object of the class where it is used. In other words,
'this' refers the object of the present class.
Generally, we write instance variables, constructors and methods in a class. All these
members are referenced by 'this'. When an object is created to a class, a default
reference is also created internally to the object.
Page 59
JAVA PROGRAMMING UNIT-1
{
return num*fact(num-1);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter number: ");
long num=sc.nextInt();
long f=Factorial.fact(num);
System.out.println("Factorial is "+f);
}
}
Command line arguments:
The java command-line argument is an argument i.e. passed at the time of running the
java program.
The arguments passed from the console can be received in the java program and it can be
used as an input.
So, it provides a convenient way to check the behaviour of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Example: Write a JAVA Program to read input from command line.
class CommandLine
{
public static void main(String[] args)
{
System.out.println("Command line argument values are ");
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
Output:
Command line argument values are
27
2.5
krishna
Nested Classes:
Nested classes are the classes that contain other classes like inner classes. Inner class is
basically a safety mechanism since it is hidden from other classes in its outer class.
To make instance variables not available outside the class, we use 'private' access
specifier before the variables. This is how we provide the security mechanism to
variables. Similarly, in some cases we want to provide security for the entire class.
In this case, can we use 'private' access specifier before the class? The problem is, if we
Page 60
JAVA PROGRAMMING UNIT-1
use private access specifier before a class, the class is not available to the Java compiler
or JVM. SO it is illegal to use 'private' before a class name in Java.
But, private specifier is allowed before an inner class and thus it is useful to provide
security for the entire inner class.
An inner class is a class that is defined inside another class.
Inner class is a safety mechanism.
Inner class is hidden from other classes in its outer class.
An object to inner class cannot be created in other classes.
An object to inner class can be created only in its outer class.
Inner class _can access the members of outer class directly.
Inner class object and outer class objects are created in separate memory locations.
Page 61
JAVA PROGRAMMING UNIT-1
Example: Write a JAVA program to create the outer class BankAccount and the inner class
Interest in it.
import java.util.Scanner;
class BankAccount
{
double bal;
BankAccount(double b)
{
bal=b;
}
void contact(double r)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Password: ");
String password=sc.next();
if(password.equals("cse556"))
{
Interest in=new Interest(r);
in.calculateInterest();
}
}
private class Interest
{
double rate;
Interest(double r)
{
rate=r;
}
void calculateInterest()
{
double inter=bal*rate/100;
bal=bal+inter;
System.out.println("Updated Balance= "+bal);
}
}
public static void main(String[] args)
{
BankAccount ba=new BankAccount(10000);
ba.contact(9.5);
}
}
Output:
Enter Password: cse556
Updated Balance= 10950.0
Page 1
JAVA PROGRAMMING UNIT-1
Strings:
In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string.
String is a class in java.lang package. But in java, all classes are also considered as data
types. So, we can take string as a data type also. A class is also called as user-defined data
type.
Creating Strings:
There are three ways to create strings in Java:
We can create a string just by assigning a group of characters to a string type variable:
String s;
s = "Hello";
Preceding two statements can be combined and written as:
String s = "Hello";
In this, case JVM creates an object and stores the string: "Hello" in that object. This object is
referenced by the variable's'. Remember, creating object means allotting memory for storing
data.
We can create an object to String class by allocating memory using new operator. This
is just like creating an object to any class, like given here:
String s = new String("Hello");
Here, we are doing two things. First, we are creating object using new operator. Then,
we are storing the string: "Hello" into the object.
The third way of creating the strings is by converting the character arrays into strings.
Let us take a character type array: arr[] With some characters, as:
char arr[]={'H','e','l','l','o'};
Now create a string object, by pass.ing the array name to it, as:
String s = new String(arr);
String Methods:
No. Method Description
char charAt(int index) returns char value for the particular
1
index
2 int length() returns string length
static String format(String returns formatted string
3 format, Object... args)
String substring(int beginIndex, returns substring for given begin index
4 int endIndex) and end index
boolean contains(CharSequence s) returns true or false after matching the
5
sequence of char value
static String join(CharSequence returns a joined string
6 delimiter, CharSequence...
elements)
7 boolean equals(Object another) checks the equality of string with object
8 boolean isEmpty() checks if string is empty
9 String concat(String str) concatenates specified string
String replace(char old, char replaces all occurrences of specified
10 new) char value
static String Compares another string. It doesn't
11 equalsIgnoreCase(String another) check case.
Page 2
JAVA PROGRAMMING UNIT-1
Page 3
JAVA PROGRAMMING UNIT-1
StringBuffer Class:
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.
String class objects are immutable and hence their contents cannot be modified.
StringBuffer class objects are mutable; so they can be modified. Moreover the methods
that directly manipulate data of the object are not available in String class. Such methods
are available in StringBuffer class.
Creating StringBuffer objects:
We can create StringBuffer object by using new operator and pass the string to the object, as:
StringBuffer sb = new StringBuffer("Hello");
Page 4
JAVA PROGRAMMING UNIT-1
Page 5
JAVA PROGRAMMING UNIT-1
This package contains a lot of classes, all of which can be classified into two basic
categories: input streams and output streams.
Keyboard is represented by a field, called in System class. When we write System.in,
we are representing a standard input device, i.e. keyboard, by default. System class is
found in java.lang (language) package and has three fields' as shown below.
All these fields represent some type of stream:
System.in: This represents Ii1putStream object, which by default represents
standard input device, i.e., keyboard.
System.out: This represents PrintStream object, which by default represents
standard output device, i.e., monitor.
System.err: This field also represents PrintStream object, which by default
represents monitor.
Note that both System.out and System.err can be used to represent the monitor and hence
any of these two can be used to send data to the monitor.
To accept data from the keyboard i.e., System.in. we need to connect it to an input stream.
And input stream is needed to read data from the keyboard.
Connect the keyboard to an input stream object. Here, we can use InputStreamReader that
can read data from the keyboard.
InputStreamReader isr = new InputStreamReader(System.in);
Connect InputStreamReader to BufferedReader, which is another input type of stream.
BufferedReader br = new BufferedReader(isr);
Now we can read data coming from the keyboard using read( ) and readLine( ) methods
available in BufferedReader class.
Ex: Write a JAVA Program to read Single character from the keyboard.
import java.io.*;
import java.lang.*;
class Test {
public static void main(String[] args)throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print("Enter a single Character: ");
char ch = (char)br.read();
System.out.print("\n The Character is "+ch);
}
}
Output:
javac Test.java
java Test
Enter a single Character: m
The Character is m
Page 6
JAVA PROGRAMMING UNIT-1
Page 7
JAVA PROGRAMMING UNIT-1
}
}
Output:
javac Test.java
java Test
Enter id name sal: 09 sudheer 40000.00
Id is: 09
Name is: sudheer
Sal is: 40000.00
Page 25
JAVA PROGRAMMING UNIT-1
TUTORIAL QUESTIONS
1.7
2 Explain about Buzzwords in java?
1.1
3 Need for OOPs Paradigm?
1.13
3 How to identify the literals and expression?
Write about garbage collection in java? 1.21
4
1.20
5 What is this keyword in java and describe with an example?
1.26
3 Explain about method overriding?
Give an example program for recursion? 1.27
4
Page 26
JAVA PROGRAMMING UNIT-1
University Questions
R16
Code No: 136FM
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD
B. Tech III Year II Semester Examinations, May - 2019
JAVA PROGRAMMING
(Common to CE, EEE, ME, ECE, EIE, MSNT)
Time: 3 hours Max. Marks: 75
Note: This question paper contains two parts A and B.
Part A is compulsory which carries 25 marks. Answer all questions in Part A. Part B consists of 5
Units. Answer any one full question from each unit. Each question carries 10 marks and may have a, b,
c as sub questions.
PART - A
(25 Marks)
1.a) Define polymorphism. [2]
b) Why is byte code of Java is known as magical code? [3]
c) What is an inner class? [2]
d) Differentiate between interface and abstract class. [3]
e) List checked exceptions of Java. [2]
f) How to create a thread? [3]
g) What is a ResultSet? [2]
h) How is a vector different from an array? [3]
i) Why swing components are light weight? [2]
j) Give AWT hierarchy and swing hierarchy. [3]
PART - B
(50 Marks)
2. Make a comparison of procedure oriented programming and object oriented programming. [10]
OR
3.a) How does Java support type casting?
b) Demonstrate the use of ‘this’ keyword. [5+5]
4. Describe different forms of inheritance. Write a program to implement multiple inheritance. [10]
OR
5.a) What is meant by dynamic binding? Explain dynamic method dispatch.
b) Describe the need of package creation in Java. [5+5]
6. What is an exception? What are the benefits of exception handling? Explain the five keywords of
Java important for exception handling. [10]
OR
7.a) Differentiate between process and thread.
b) Write a program to solve producer-consumer problem using inter-thread communication. [5+5]
www.manaresults.co.in
Page 27
JAVA PROGRAMMING UNIT-1
8. Write a Java program to append second file content to first file, read two file names as command line
arguments. [10]
OR
9.a) Describe the four types of database drivers of JDBC.
b) Describe the important methods of StringTokenizer class. [5+5]
10. What is an event? Describe delegation event model and write a program to handle mouse events.
[10]
OR
11. Compare applets with application programs. With suitable program segments explain applet life
cycle. [10]
Page 28
JAVA PROGRAMMING UNIT-1
8. Write a program to read a file content and extract words using String Tokenizer class. Display the
file if it contains the user query term/search key. [10]
OR
9.a) Contrast sorted map and navigable map interfaces.
b) What is the purpose of BitSet class? What is the functionality of the following functions of BitSet
class: cardinality( ) , flip( ) and intersects( ) [5+5]
10.a) Illustrate the use of Grid Bag layout.
b) What are the subclasses of JButton class of swing package? [5+5]
OR
11.a) Create a simple applet to display a smiley picture using Graphics class methods.
b) Write a short note on delegation event model. [5+5]
Page 29
JAVA PROGRAMMING UNIT-1
DESCRIPTIVE QUESTIONS
2. Can a method be overloaded based on different return type but same argument type? TL 1 CO 1
a) Explain Summarize the following object oriented concepts.
Abstraction ii) Polymorphism
3. TL 3 CO 1
b) "Java is called Machine Independent language" - Justify this statement with proper
explanation.
a) What do you mean by static class and static method? Can we make an instance of an
4. TL 2 CO 1
abstract class? Justify your answer with an example?
a) Define the different forms of inheritance?
5. TL 3 CO 2
b) Define java Buzzwords?
a) Justify why the features of Object Oriented Programming are important for
programming?
6. TL 3 CO 2
b) List out the characteristics of the static method.
a) "Write Once and Run Anywhere" - Support this statement with proper reasoning.
9. b) Define a constructor? When does the compiler supply default constructor for a TL 4 CO 3
class?
13. b) Explain clearly about how Java handles cleaning up of unused objects. TL 1 CO 1
a) Define the use of super keyword?
14. b) Distinguish between abstract class and concrete class. TL 3 CO 2
Page 30
JAVA PROGRAMMING UNIT-1
OBJECTIVE QUESTIONS
1) Which of the following option leads to the portability and security of Java?
a. Dynamic
b. Architecture Neutral
c. Use of pointers
d. Object-oriented
5. Which concept of Java is achieved by combining methods and attribute into a class?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction
7. When a method having same method name with different signatures are called------
a) Operator Overloading
Page 31
JAVA PROGRAMMING UNIT-1
b) Method Overriding
c) Constructor Overloading
d) Method Overloading
a) If and else-if-ladder
b) While
c) For
d) Abstract
Page 32
JAVA PROGRAMMING UNIT-1
SET-1
PART – 1 Objective Questions: 10*0.5=5 Marks
1. A Class can be defined as ………………………………………….
9. ……………….. keyword is used to invoke the current class methods and attributes.
10. Converting a lower datatype into another data type is known as ………………………
Or
SET-2
PART – 1 Objective Questions: 10*0.5=5 Marks
1. Which oops concept is used to perform in different ways …………………….
5. ……………….. keyword is used to invoke the current class methods and attributes.
Or
2. a) Define the variable and describe the scope and life time of a variable?
8. ……………….. keyword is used to invoke the current class methods and attributes.
Or
3. ……………….. keyword is used to invoke the current class methods and attributes.
Or
2. a) Define the variable and describe the scope and life time of a variable?
Page 35
JAVA PROGRAMMING UNIT-1
SEMINAR TOPICS
Page 36
JAVA PROGRAMMING UNIT-1
ASSIGNMENT QUESTIONS
Page 37
JAVA PROGRAMMING UNIT-1
Balance Withdraw ()
Balance Enquiry ()
Amount Deposit ()
Pin change ()
From customer/ User perspective, need to use or operate the functions which are provided by the
ATM machine or application.
Here, customer can view the operation but he can’t understand the application how it is
implemented and what logic used to run the application.
Page 38
JAVA PROGRAMMING UNIT-1
1.What is JVM?
The Java interpreter along with the runtime environment required to run the Java application in called as
Java virtual machine(JVM)
Platform independence means that we can write and compile the java code in one platform (eg
Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).
JDK is Java Development Kit which is for development purpose and it includes execution environment
also. But JVM is purely a run time environment and hence you will not be able to compile your source
files using a JVM.
java.lang.Object
There are 3 access modifiers. Public, protected and private, and the default one if no identifier is
specified is called friendly, but programmer cannot specify the friendly identifier explicitly.
Global variables are globally accessible. Java does not support globally accessible variables due to
following reasons:
1)The global variables breaks the referential transparency
2)Global variables creates collisions in namespace.
Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe
from outside interference and misuse. Inheritance is the process by which one object acquires the
properties of another object. Polymorphism is the feature that allows one interface to be used for
general class actions.
Method overloading: When a method in a class having the same method name with different arguments
is said to be method overloading. Method overriding : When a method in a class having the same
method name with same arguments is said to be method overriding.
this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a
super class constructor.
Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline
computations. So you can’t look at the whole method, rank the expressions according to which ones are
re-used the most, and then generate code. In theory terms, it’s an on-line problem.
public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as
private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by
classes in the same package and subclasses in the other packages. default modifier : Can be accessed
only to classes in the same package.
A constructor is a member function of a class that is used to create objects of that class. It has the same
name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be
void),and is invoked using the dot operator.
15.What is UNICODE?
Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each
other.
Page 40
JAVA PROGRAMMING UNIT-1
THINKING ABILTY
Object-oriented programming has four basic concepts: encapsulation, abstraction, inheritance and
polymorphism. Even if these concepts seem incredibly complex, understanding the general
framework of how they work will help you understand the basics of a computer program. Here are
the four basic theories and what they entail:
Encapsulation, Abstraction, Inheritance and Polymorphism
Beginning programmers may better understand this concept in relation to how a browser
functions. Browsers have local storage objects that allow you to store data locally. These objects
have properties, like length, which turns the number of objects into storage, along with methods
like (remove item) and (set item).
Think of a stereo system as an object with a complex logic board on the inside. It has buttons on
the outside to allow for interaction with the object. When you press any of the buttons, you're not
thinking about what happens on the inside because you can't see it. Even though you can't see the
logic board completing functions as a result of pressing a button, it's still performing actions. This is
an abstraction, which can be used to understand the concept of programming.
Another way to understand this is to consider the human body. The skin acts as an abstraction to
hide the internal body parts responsible for bodily functions like digesting and walking.
Consider two classes. One is the superclass (parent) while the subclass (child) will inherit the
properties of the parent class and modify its behavior. Programmers applying the technique of
inheritance arrange these classes into a hierarchy of "is-a-type-of" relationships.
For instance, in the animal world, an insect would be a superclass. All insects share similar
properties, such as having six legs and an exoskeleton. Grasshoppers and ants are both insects and
inherited similar properties.
To better understand the two terms of polymorphism called overloading and overriding, it helps to
visualize the process of walking. Babies learn to crawl first by using their arms and legs. Once they
learn to stand and walk, they are ultimately changing the body part used to accomplish the act of
walking. This term of polymorphism is called overloading. To understand the next term of
overriding, think of how you naturally walk in the direction you are facing. When you stop and walk
backward, this changes the direction of your path and also the mechanism of function. You are
overriding the natural action that you usually complete.
Page 41