Sie sind auf Seite 1von 28

WebTeks Labs

TRAINING ON CORE JAVA

UNIVERSITY OF ENGINEERING
&
MANAGEMENT, JAIPUR

SUBMITTED BY:

SAURABH KUMAR

Enrollment No – 12016002001037

Department of Computer Science And Engineering


Approval Certificate

This is to certify that the project report entitled “Training on core java”
submitted by Saurabh Kumar (Roll:12016002001037) in partial fulfillment
of the requirements of the degree of Bachelor of Technology in Computer
Science & Engineering from University of Engineering and Management,
Jaipur was carried out in a systematic and procedural manner to the best
of our knowledge. It is a bona fide work of the candidate and was carried
out under our supervision and guidance during the academic session of
2016-2020.

_______________________

Prof. Sauvik Bal


Project Guide, Assistant Professor (CSE)
UEM, JAIPUR

_______________________ ______________________

Prof. Mrinal Kanti Sarkar Prof. A Mukherjee


HOD (CSE) Dean
UEM, JAIPUR UEM, JAIPUR
ACKNOWLEDGEMENT

The endless thanks goes to Lord Almighty for all the blessings he has
showered onto me, which has enabled me to write this last note in my
research work. During the period of my research, as in the rest of my life, I
have been blessed by Almighty with some extraordinary people who have
spun a web of support around me. Words can never be enough in
expressing how grateful I am to those incredible people in my life who
made this thesis possible. I would like an attempt to thank them for
making my time during my research in the Institute a period I will
treasure. I am deeply indebted to my research supervisor, Professor
Sauvik Bal to give me such an interesting thesis topic. Each meeting with
him added in valuable aspects to the implementation and broadened my
perspective. He has guided me with his invaluable suggestions, lightened
up the way in my darkest times and encouraged me a lot in the academic
life.

SAURABH KUMAR
TRAINING ON CORE JAVA
WEBTEK LABS

5/6/2017

WEBTEK LABS

DEPARTEMENT OF COMPUTER SCIENCE & ENGINEERING


UNIVERSITY OF ENGINEERING AND MANAGEMENT

Introduction to Java
Java is one of the world's most important and widely used computer
languages, and it has held this distinction for many years. Unlike some other
computer languages whose influence has weared with passage of time, while
Java's has grown.
As of 2015, Java is one of the most popular programming languages in use,
particularly for client-server web applications, with a reported 9 million
developers using and working on it.
Evolution of Java
Java was initially launched as Java 1.0 but soon after its initial release, Java 1.1
was launched. Java 1.1 redefined event handling, new library elements were
added.
In Java 1.2 Swing and Collection framework was added
and suspend(), resume()and stop()methods were deprecated from Thread class.

No major changes were made into Java 1.3 but the next release that was Java
1.4 contained several important changes. Keywordassert, chained exceptions
and channel based I/O System wasintroduced.
Java 1.5 was called J2SE 5, it added following major new features :

 Generics
 Annotations
 Autoboxing andautounboxing
 Enumerations
 For-eachLoop

Application of Java
Java is widely used in every corner of world and of human life. Java is not only
used in softwares but is also widely used in designing hardware controlling
software components. There are more than 930 million JRE downloads each
year and 3 billion mobile phones run java.
Following are some other usage of Java :

1. Developing DesktopApplications
2. Web Applications like Linkedin.com, Snapdeal.cometc
3. Mobile Operating System likeAndroid
4. EmbeddedSystems
Difference between JDK andJRE
JRE : The Java Runtime Environment (JRE) provides the libraries, the Java Virtual
Machine, and other components to run applets and applications written in the
Java programming language. JRE does not contain tools and utilities such as
compilersor debuggers for developing applets andapplications.
JDK : The JDK also called Java Development Kit is a superset of the JRE,
and contains everything that is in the JRE, plus tools such as the
compilers and debuggers necessary for developing applets and
applications.
FIRST JAVA PROGRAM
classHello

public static void main(String[] args)

System.out.println ("Hello World program");

}
Class
} : class keyword is used to declare classes in Java
Public : It is an access specifier. Public means this function is visible to all.
Static : static is again a keyword used to make a function static. To execute a
static function you do not have to create an Object of the class. The main()
method here is called by JVM, without creating any object for class.
Void : It is the return type, meaning this function will not return anything.
Main : main() method is the most important method in a Java program. This is
the method which is executed, hence all the logic must be inside the main()
method. If a java class is not having a main() method, it causes compilation
error.
String[] args : This represents an array whose type is String and name is args.
We will discuss more about array in Java Array section.
System.out.println : This is used to print anything on the console like
printf in C language.

Steps to Compile and Run your first Java


program
Step 1: Open a text editor and write the code as above.
Step 2: Save the file as Hello.java

Step 3: Open command prompt and go to the directory where you saved
your first java program assuming it is saved in C:\
Step 4: Type javac Hello.javaand press Return(Enter KEY) to compile your code.
This command will call the Java Compiler asking it to compile the specified file.
If there are no errors in the code the command prompt will take you to the
next line.
Step 5: Now type java Helloon command prompt to run your program.

Step 6: You will be able to see Hello world program .


A primitive data type can be of eight types :
Primitive Data types

char boolean byte short int long float double

Once a primitive data type has been declared its type can never change,
although in most cases its value can change. These eight primitive type can be
put into four groups

Integer
This group includes byte, short, int, long

byte : It is 1 byte(8-bits) integer data type. Value range from -128 to 127.
Default value zero. example: byte b=10;
short : It is 2 bytes(16-bits) integer data type. Value range from -32768 to
32767. Default value zero. example: short s=11;
int : It is 4 bytes(32-bits) integer data type. Value range from -
2147483648 to 2147483647. Default value zero. example: int i=10;
long : It is 8 bytes(64-bits) integer data type. Value range from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Default value
zero.
example: longl=100012;

Floating-PointNumber
This group includes float, double

float : It is 4 bytes(32-bits) float data type. Default value 0.0f. example:


floatff=10.3f;
double : It is 8 bytes(64-bits) float data type. Default value 0.0d.
example: doubledb=11.123;

Characters
This group represent char, which represent symbols in a character set, like
letters and numbers.
char : It is 2 bytes(16-bits) unsigned unicode character. Range 0 to
65,535. example: char c='a';
Identifiers in Java
All Java components require names. Name used for classes, methods,
interfaces and variables are called Identifier. Identifier must follow some
rules. Here are the rules:

 Allidentifiers

muststartwitheitheraletter(atozorAtoZ)orcurrencycharacter($) or an

underscore.

 After the first character, an identifier can have any combination


ofcharacters.
 A Java keyword cannot be used as anidentifier.
 Identifiers in Java are case sensitive, foo and Foo are two
differentidentifiers.

Variable in Java
When we want to store any information, we store it in an address of the
computer.The naming of an address is known as variable. Variable is the name
of memory location.Java Programming language defines mainly three kind of
variables.

1. Instancevariables

2. StaticVariables

3. LocalVariables

Instance variables in Java


Instance variables are variables that are declare inside a class but outside any
method,constructor or block. Instance variable are also variable of object
commonly known as field or property. They are referred as object variable.
Each object has its own copy of each variable and thus, it doesn't effect the
instance variable if one object changes the value of the variable.
classStudent

String name;
intage;

}
Here name and age are instance variable of Student class.
Static variables in Java
Static are class variables declared with static keyword. Static variables are
initialized only once. Static variables are also used in declaring constant along
with final keyword.
classStudent

String name;
intage;

staticintinstituteCode=1101;

Concept of Array in Java


An array is a collection of similar data types. Array is a container object that
hold values of homogenous type. It is also known as static data structure
because size of an array must be specified at the time of its declaration.
An array can be either primitive or reference type. It gets memory in
heap area. Index of array starts from zero to size-1.

Features of Array
 It is always indexed. Index begins from0.
 It is a collection of similar datatypes.
 It occupies a contiguous memorylocation.

Array Declaration
Syntax :

datatype[] identifier;
or

datatype identifier[];
Java Operators
Java provides a rich set of operators environment. Java operators can be
divided into following categories:

 Arithmeticoperators
 Relationoperators
 Logicaloperators
 Bitwiseoperators
 Assignmentoperators
 Conditionaloperators
 Miscoperators

Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way
that are used in algebra.

Operator Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denumerator

% remainder of division

++ Increment operator increases integer value by one

-- Decrement operator decreases integer value by one


Relation operators
The following table shows all relation operators supported by Java.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false


Bitwise operators
Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Assignment Operators
Operato Description Example
r
= assigns values from right side operands to left side a=b
operand
+= adds right operand to the left operand and assign a+=b is
the result to left same as
a=a+b
-= subtracts right operand from the left operand and a-=bis same
assign the result to left operand as a=a-b

*= mutiply left operand with the right operand and a*=b is


assign the result to left operand same as
a=a*b
/= divides left operand with the right operand and a/=b is
assign the result to left operand same as
a=a/b
%= calculate modulus using two operands and assign the a%=b is same
result
Java Class
In Java everything is encapsulated under classes. Class is the core of Java
language. Class can be defined as a template/ blueprint that describe the
behaviours
/states of a particular entity. A class defines new data type. Once defined
this new type can be used to create object of that type .Object is an instance
of class. You may also call it as physical existence of a logical template class.
A class is declared using class keyword. A class contain both data and code
that operate on that data. The data or variables defined within a class are
called instance variables and the code that operates on this data is
known as methods. Thus, the instance variables and methods are
known as class members. class is also known as a user defined data
type.

Rules for Java Class

 A class can have only public or default(no modifier) accessspecifier.


 It can be either abstract, final or concrete (normalclass).
 It must have the class keyword, and class must be followed by a
legalidentifier.
 It may optionally extend one parent class. By default, it will
extendjava.lang.Object.
 It may optionally implement any number of comma-separatedinterfaces.
 The class's variables and methods are declared within a set of curly braces{}.
 Each .java source file may contain only one public class. A source file

may contain any number of default visibleclasses.


 Finally, the source file name must match the public class name and it must
havea
.java suffix.

classStudent.

 {
 String name;
 introllno;
 intage;
 }
Constructors in Java

A constructor is a special method that is used to initialize an object .Every


class has a constructor, if we don't explicitly declare a constructor for any java
class the compiler builds a default constructor for that class. A constructor
does not have any returntype.
A constructor has same name as the class in which it resides. Constructor in
Java cannot be abstract, static, final or synchronized. These modifiers are not
allowed for constructor.

classCar

String name ;
String model;

Car() //Constructor

name="";

model="";

Types of Constructor
There are two types of constructors:

 DefaultConstructor
 Parameterizedconstructor
 Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked

Constructor Overloading

Like methods, a constructor can also be overloaded. Overloaded


constructors are differentiated on the basis of their type of parameters or
number of parameters.
Constructor overloading is not much different than method overloading. In
case of method overloading you have multiple methods with same name but
different signature, whereas in Constructor overloading you have multiple
constructor with different signature but only difference is that Constructor
doesn't have return type in Java.
classCricketer

String name;
String team;
intage;

Cricketer () //default constructor.

name ="";

team ="";
age = 0;

Cricketer(String n, String t,inta) //constructor overloaded

name = n;
team = t;
age = a;

Cricketer(Cricketerckt) //constructor similar to copy constructor ofc++

name = ckt.name;
team = ckt.team;
age = ckt.age;

publicString toString()

{
{

public static void main (String[] args)

Cricketer c1 = new Cricketer();

Cricketer c2 = new Cricketer("sachin", "India", 32);


Cricketer c3 = new Cricketer(c2 );
System.out.println(c2);

System.out.println(c3);
c1.name = "Virat";
c1.team= "India";
c1.age = 32;

System .out. print in (c1);

What
}
is constructor chaining in Java?
}
Constructor chaining is a phenomena of calling one constructor from
another constructor of same class. Since constructor can only be called
from another constructor in Java, constructor chaining is used for this
purpose.

classTest

Test()

this(10);

Test(intx)

System.out.println("x="+x);

public static void main(String arg[])

Test object = new Test();

}
Java thiskeyword
 this keyword is used to refer to currentobject.
 this is always a reference to the object on which method wasinvoked.
 this can be used to invoke current classconstructor.
 this can be passed as an argument to anothermethod.

 class Box
 {
 Double width, height,depth;
 Box (double w, double h, doubled)
 {
 this.width =w;
 this.height =h;
 this.depth =d;
 }
 }
 Here the this is used to initialize member of current object.Such
as, this.width refers to the variable width of the current object that
has invoked the constructor. width only refers to the parameter
received in the constructor i.e the argument passed while calling the
constructor.

The this is used to call overloaded constructor in java


classCar

privateString name;
public Car()

{this("BMW"); //oveloaded constructor is called.

}
publicCar(String n)

this.name=n; //member is initialized usingthis.

}
Access and Non-Access Modifiers in Java

Modifiers are keywords in Java that are used to change the meaning of a variable
or method. In Java, modifiers are categorized into two types:

1. Access controlmodifier

2. Non Access Modifier

Java: Access Control Modifier


Java language has four access modifier to control access levels for classes,
variable methods and constructor.

 Default: Default has scope only inside the samepackage


 Public: Public has scope that is visibleeverywhere
 Protected: Protected has scope within the package and all subclasses
 Private: Private has scope only within theclasses

Java: Non-access Modifier


Non-access modifiers do not change the accessibility of variables and
methods, but they do provide them special properties. Non-access modifiers
are of 5 types,

1. Final
2. Static
3. Transient
4. Synchronized
5. Volatile
Inheritance (IS-A relationship) in Java

Inheritance is one of the key features of Object Oriented Programming.


Inheritance provided mechanism that allowed a class to inherit property of
another class.
When a Class extends another class it inherits all non-private members
including fields and methods. Inheritance in Java can be best understood in
terms of Parent and Child relationship, also known as Super class(Parent) and
Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub
class. extendsand implementskeywords are used to describe inheritance in Java.

Purpose of Inheritance

1. It promotes the code reusabilty i.e the same methods and variables

which are defined in a parent/super/base class can be used in the

child/sub/derivedclass.

2. It promotes polymorphism by allowing methodoverriding.

Example Of Inheritance:

3. class Parent 4. {
5. public voidp1()
6. {
7. System.out.println("Parent method"); 8. }
9. }
10.public class Child extends Parent { 11.
12. public voidc1()
13. {
14. System.out.println("Childmethod");
15. }
16. public static void main(String[]args)
17. {
18. Child cobj = new Child();

19. cobj.c1(); //method of Child class


20. cobj.p1(); //method of Parent class
21. }
22.}
Method Overriding in Java
When a method in a sub class has same name, same number of arguments
and same type signature as a method in its super class, then the method is
known as overridden method. Method overriding is also referred to as
runtime polymorphism. The key benefit of overriding is the ability to define
method that's specific to a particular subclass type.
classAnimal

public void eat()

System.out.println("Generic Animal eating");

classDog extends Animal

public voideat() //eat() method overriden by Dogclass.

Difference between Overloading


System.out.println("Dog and Overriding
eat meat");

}
Method overloading and Method overriding seems to be similar concepts
but they are not. Let's see some differences between both of them:
}

Method Overloading Method Overriding

Parameter must be Both name and parameter must be same.


different and name must
be same.
Compile time polymorphism. Runtime polymorphism.

Increase readability of code. Increase reusability of code.

Access specifier can be Access specifier cannot be more restrictive


changed. than original method(can be less restrictive).
Command line argument in Java
The command line argument is the argument passed to a program at the time when you
run it. To access the command-line argument inside a java program is quite easy, they are
stored as string in String array passed to the args parameter
of main()method.

classcmd

public static void main(String[] args)

for(inti=0;i<args.length;i++)

System.out.println(args[i]);

}
Execute this program as java cmd 10 20 30
}

}
Interfaces in Java
Interface is a pure abstract class .They are syntactically similar to classes, but
you cannot create instance of an Interface and their methods are declared
without any body. Interface is used to achieve complete abstraction in Java.
When you create an interface it defines what a class can do without saying
anything about how the class will do it.

Rules for using Interface


 Methods inside Interface must not be static, final, native orstrictfp.
 All variables declared inside interface are implicitly public

static final variables(constants).

 All methods declared inside Java Interfaces are implicitly public and

abstract, even if you don't use public or abstractkeyword.


 Interface can extend one or more otherinterface.
 Interface cannot implement aclass.
 Interface can be nested inside anotherinterface.
Example of Interface implementation

interfaceMoveable

intAVG-SPEED = 40;

voidmove();

classVehicle implements Moveable

public void move()

System .out. print in ("Average speed is"+AVG-SPEED");

public static void main (String[] arg)

Difference Vehicle
between an Vehicle();
vc = new interface and an abstract class?
vc.move();

} Abstract class Interfac


} e
Abstract class is a class Interface is a Java Object containing method
which contain one or more declaration but no implementation. The
abstract methods, which classes which implement the Interfaces must
has to be implemented by provide the method definition for all the
its sub classes. methods.
Abstract class is a Class prefix Interface is a pure abstract class which
with an abstract keyword starts with interface keyword.
followed by Class definition.

Abstract class can also Whereas, Interface contains all abstract


contain concrete methods and final variable declarations.
methods.
CONCLUSION
This report delved into object-oriented programming (OOP) and its relevance
to Java.this report started by learning objects and classes, which form the basis
for OOP.Java is an object-oriented programming (OOP) language. Object
orientation helps a developer to achieve a modular, extensible, maintainable,
and reusable system. Object-oriented programming revolves around the
concept of an object, which encapsulates data and behavior acting on the data
together.Java offers the real possibility that most programs can be written in a
type-safe language. However, for Java to be broadly useful, it needs to have more
expressive power than it does at present.It extends Java with a mechanism for
parametric polymorphism, which allows the definition and implementation of
generic abstractions. The paper gives a complete design for the extended
language. The proposed extension is small and conservative and the paper
discusses the rationale for many of our decisions. The extension does have some
impact on other parts of Java, especially Java arrays, and the Java class library.
Java is considered to be the most reliable tool for developing client server
application. Efficient exploration and implementing of such functionalities of
java has lead to practical challenging research activities and development of
new standards, thereby shrinking the communication gap.
Java defined the client server architecture and the powerful tool for network.

.
CONTENTS
 INTRODUCTION
 DIFFERENCE BETWEEN JDK AND JRE
 PRIMITIVE DATATYPES
 STATIC VARIABLE
 ARRAY
 OPERATORS
 CONSTRUCTOR
 THIS KEYWORD
 MODIFIERS
 INHERITANCE
 COMMAND LINE ARGUMENT
 INTERFACE
 CONCLUSION
 REFERENCE
REFERENCES
 www.google.com
 www.wikipedia.com
 www.studymafia.org
 www.javatutorialpoint.com

Das könnte Ihnen auch gefallen