Sei sulla pagina 1di 21

Java Programming Language

A Course Report
(Course Report for the partial fulfillment in awarding the degree of B.Tech in Computer

Science & Engineering.)

Submitted by

Aman Karakoti

(Roll No. 180050101004)

Under the Supervision & Guidance of

Mr. NITIN CHHIMWAL

Submitted to:

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

BIRLA INSTITUTE OF APPLIED SCIENCES, BHIMTAL

NAINITAL (UTTARAKHAND) - 263136

August 2019
Sr.No. CONTENT
1 Acknowledgement
2 Introduction
3 History
4 Classes and Objects
5 Methods in Java
6 Java conditional Statements
7 Java loop statements
8 Conclusion
9 Result
10 Preferences
Acknowledgement

I like to express my deep sense of gratitude to my Mentor Dr. Sandesh Tripathi coordinator of
Department of Computer Science & Engineering, Birla Institute of Applied Sciences, Bhimtal,
Uttarakhand for his guidance, keen interest, constant encouragement and helpful criticism. His
advices were invaluable even when the going got tough during the course of the study embodied
in this project.

My deepest gratitude also goes for our respected Director Sir Dr. B.S. Bisht and

Co-Ordinator of the Department, Dr. Sandesh Tripathi for his valuable advice,

encouragement and all time support.

I would like to thank all faculties and staff-members of the Department of Computer

Science & Engineering, BIAS for their help and suggestions for betterment of the project.

I would also like to acknowledge the Dept. of CSE for providing Support, Enthusiasm

and other such lab facilities and the University of Dehradun , for providing infrastructure

development fund.

I would like to thank my friends and colleagues for critically reading the manuscript and

providing information at times.

I am also highly grateful to my parents for their endless support.

Name: Aman Karakoti Place: Bhimtal

Roll No : 180050101004 Date:17/08/19


References

 https://www.w3schools.com
 https://developer.mozilla.org
 https://www.udemy.com/the-web-developer-bootcamp/learn/lecture
 https://en.wikipedia.org
 https://www.tutorialspoint.com
 https://www.google.com
Introduction

Java is a simple and yet powerful object oriented programming language and it is in many
respects similar to C++. Java originated at Sun Microsystems, Inc. in 1991. It was conceived by
James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun
Microsystems, Inc. It was developed to provide a platform-independent programming language.
This site gives you an Introduction to Java Programming accompanied with many java
examples. Its a complete course in java programming for beginners to advanced java.

Platform Independent
Unlike many other programming languages including C and C++ when Java is compiled, it is not
compiled into platform specific machine, rather into platform independent byte code. This byte
code is distributed over the web and interpreted by virtual Machine (JVM) on whichever
platform it is being run.

Java Virtual Machine


What is the Java Virtual Machine? What is its role?
Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine
plays the central role in this concept. The JVM is the environment in which Java programs
execute. It is a software that is implemented on top of real hardware and operating system. When
the source code (.java files) is compiled, it is translated into byte codes and then placed into
(.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as the
machine language of the JVM. A JVM can either interpret the bytecode one instruction at a time
or the bytecode can be compiled further for the real microprocessor using what is called a just-in-
time compiler. The JVM must be implemented on a particular platform before compiled
programs can run on that platform.

Object Oriented Programming


Object Oriented Programming is a method of implementation in which programs are organized
as cooperative collection of objects, each of which represents an instance of a class, and whose
classes are all members of a hierarchy of classes united via inheritance relationships.
OOP Concepts
Four principles of Object Oriented Programming are

1.Abstraction
2.Encapsulation
3.Inheritance
4.Polymorphism
Abstraction
Abstraction denotes the essential characteristics of an object that distinguish it from all
other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the
perspective of the viewer.

Encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that


constitute its structure and behavior ; encapsulation serves to separate the contractual interface of
an abstraction and its implementation.
* Hides the implementation details of a class.
* Forces the user to use an interface to access data
* Makes the code more maintainable.

Inheritance
Inheritance is the process by which one object acquires the properties of another object.

Polymorphism
Polymorphism is the existence of the classes or methods in different forms or single name
denoting different implementations.
Java has powerful features. The following are some of them:-
Since Java is an object oriented programming language it has following features:
Reusability of Code
Emphasis on data rather than procedure
Data is hidden and cannot be accessed by external functions
Objects can communicate with each other through functions
New data and functions can be easily added

Java Is Distributed
With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and
access the objects across net via URLs.
Java Is Multithreaded
One of the powerful aspects of the Java language is that it allows multiple threads of execution to
run concurrently within the same program A single Java program can have many different
threads executing independently and continuously. Multiple Java applets can run on the browser
at the same time sharing the CPU time.

Java Is Secure
Java was designed to allow secure execution of code across network. To make Java secure many
of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot
access arbitrary addresses in memory.

Garbage Collection
Automatic garbage collection is another great feature of Java with which it prevents inadvertent
corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap
for a new object. But it does not use delete operator to free the memory as it is done in C++ to
free the memory if the object is no longer needed. It is done automatically with garbage
collector.

Java Applications
Java has evolved from a simple language providing interactive dynamic content for web pages to
a predominant enterprise-enabled programming language suitable for developing significant and
critical applications. Today, It is used for many types of applications including Web based
applications, Financial applications, Gaming applications, embedded systems, Distributed
enterprise applications, mobile applications, Image processors, desktop applications and many
more.
History Of Java
In the early 90s, extending the power of network computing to the activities of everyday life was
a radical vision. In 1991, a small group of Sun engineers called the "Green Team" believed that
the next wave in computing was the union of digital consumer devices and computers. Led by
James Gosling, the team worked around the clock and created the programming language that
would revolutionize our world – Java.
The Green Team demonstrated their new language with an interactive, handheld home-
entertainment controller that was originally targeted at the digital cable television industry.
Unfortunately, the concept was much too advanced for the team at the time. But it was just right
for the Internet, which was just starting to take off. In 1995, the team announced that the
Netscape Navigator Internet browser would incorporate Java technology.
Today, Java not only permeates the Internet, but also is the invisible force behind many of the
applications and devices that power our day-to-day lives. From mobile phones to handheld
devices, games and navigation systems to e-business solutions, Java is everywhere!
Classes and Objects in Java
Classes and Objects are basic concepts of Object Oriented Programming which revolve around
the real life entities.

Class

A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers : A class can be public or has default access Class name: The name should
begin with a initial letter (capitalized by convention).

2. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.

3. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if


any, preceded by the keyword implements. A class can implement more than one
interface.

4. Body: The class body surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provides the state of
the class and its objects, and methods are used to implement the behavior of the class and its
objects.
There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.
Object

It is a basic unit of Object Oriented Programming and represents the real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An object
consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an
object.

2. Behavior : It is represented by methods of an object. It also reflects the response of an


object with other objects.

3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.

Example of an object : dog

Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might have objects such
as “shopping cart”, “customer”, and “product”.
Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share
the attributes and the behavior of the class. But the values of those attributes, i.e. the state are
unique for each object. A single class may have any number of instances.
Example :

This notifies the compiler that we will use name to refer to data whose type is type. With a
primitive variable, this declaration also reserves the proper amount of memory for the variable.
So for reference variable, type must be strictly a concrete class name. In general,we can’t create
objects of an abstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an
object is actually created and assigned to it. Simply declaring a reference variable does not create
an object.

Ways to create object of a class

There are four ways to create objects in java.Strictly speaking there is only one way(by
using new keyword),and the rest internally use newkeyword.
 Using new keyword : It is the most common and general way to create object in
java. Example:

 // creating object of class Test


 Test t = new Test();

 Using Class.forName(String className) method : There is a pre-defined class in


java.lang package with name Class. The forName(String className) method returns the
Class object associated with the class with the given string name.We have to give the fully
qualified name for a class. On calling new Instance() method on this Class object returns
new instance of the class with the given string name.
 // creating object of public class Test
 // consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();

 Using clone() method: clone() method is present in Object class. It creates and returns a
copy of the object.

 // creating object of class Test


 Test t1 = new Test();

 // creating clone of above object


 Test t2 = (Test)t1.clone();

 Deserialization : De-serialization is technique of reading an object from the saved state in


a file. Refer Serialization/De-Serialization in java

 FileInputStream file = new FileInputStream(filename);


 ObjectInputStream in = new ObjectInputStream(file);
 Object obj = in.readObject();
Creating multiple objects by one type only (A good practice)
 In real-time, we need different objects of a class in different methods. Creating a number
of references for storing them is not a good practice and therefore we declare a static
reference variable and use it whenever required. In this case,wastage of memory is less.
The objects that are not referenced anymore will be destroyed by Garbage Collector of
java. Example:

 Test test = new Test();
 test = new Test();
 In inheritance system, we use parent class reference variable to store a sub-class object. In
this case, we can switch into different subclass objects using same referenced variable.
Example:
 class Animal {}

 class Dog extends Animal {}


 class Cat extends Animal {}

 public class Test


 {
 // using Dog object
 Animal obj = new Dog();

 // using Cat object


 obj = new Cat();
 }

Anonymous objects

Anonymous objects are the objects that are instantiated but are not stored in a reference variable.
 They are used for immediate method calling.
 They will be destroyed after method calling.
 They are widely used in different libraries. For example, in AWT libraries, they are used to
perform some action on capturing an event(eg a key press).
 In example below, when a key is button(referred by the btn) is pressed, we are simply
creating anonymous object of EventHandler class for just calling handle method.
 btn.setOnAction(new EventHandler()
 {
 public void handle(ActionEvent event)
 {
 System.out.println("Hello World!");
 }
Methods in Java
A method is a collection of statements that perform some specific task and return the result to the
caller. A method can perform some specific task without returning anything. Methods allow us
to reusethe code without retyping the code. In Java, every method must be part of some class
which is different from languages like C, C++, and Python.
Methods are time savers and help us to reuse the code without retyping the code.

Method Declaration

In general, method declarations has six components :


 Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
 public: accessible in all class in your application.
 protected: accessible within the class in which it is defined and in its subclass(es)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier) : accessible within same class
and package within which its class is defined.

 The return type : The data type of the value returned by the method or void if does not
return a value.

 Method Name : the rules for field names apply to method names as well, but the
convention is a little different.

 Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().

 Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).

 Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.
Method signature: It consists of the method name and a parameter list (number of parameters,
type of the parameters and order of the parameters). The return type and exceptions are not
considered as part of it.
Method Signature of above function:
max(int x, int y)

How to name a Method?: A method name is typically a single word that should be a verb in
lowercase or multi-word, that begins with a verb in lowercase followed by adjective,
noun….. After the first word, first letter of each word should be capitalized. For example,
findSum,
computeMax, setX and getX
Generally, A method has a unique name within the class in which it is defined but sometime a
method might have the same name as other method names within the same class as method
overloading is allowed in Java.

Calling a method

The method needs to be called for using its functionality. There can be three situations
when a method is called:
A method returns to the code that invoked it when:
 It completes all the statements in the method
 It reaches a return statement
 Throws an exception
Java Conditional Statements
Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax

if (condition) {
// block of code to be executed if the condition is true
}

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Java Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional
Java Loop Statements
Java has three types of loops

Loops can execute a block of code as long as a specified condition is reached.

Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax

while (condition) {
// code block to be executed
}
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never
end!

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.

Syntax

do {
// code block to be executed
}
while (condition);
The example above uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested

Java For Loop

When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Syntax

for (statement 1; statement 2; statement 3) {


// code block to be executed
}
Conclusion

Things I have learnt:

 Classes and objects


 Java Datatypes
 Methods(Functions) in Java
 Conditional Statements(if,else,else-if,switch)
 Loop statements(for,while,do-while)
 Arrays
 Strings in Java
 Data structures in Java
 OOP concepts in Java
Result

Potrebbero piacerti anche