core java training report

40
Maharishi Markandeshwar University Page - 1 - MAHARISHI MARKANDESHWAR UNIVERSITY MULLANA, AMBALA (SESSION 2014-2018) DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING INDUSTRIAL TRAINING REPORT Submitted in Partial Fulfillment of requirements for the Award of Degree of Bachelor of Technology (Computer Science & Engineering) Head of Dept: Submitted By: Mr. Sandeep Goyal Sumit kr. Sharma 11142507

Upload: sumit-sharma

Post on 21-Jan-2018

652 views

Category:

Engineering


27 download

TRANSCRIPT

Page 1: Core Java Training report

Maharishi Markandeshwar University Page - 1 -

MAHARISHI MARKANDESHWAR UNIVERSITY

MULLANA, AMBALA

(SESSION 2014-2018)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

INDUSTRIAL TRAINING REPORT

Submitted in Partial Fulfillment of requirements for the Award of Degree of

Bachelor of Technology (Computer Science & Engineering)

Head of Dept: Submitted By:

Mr. Sandeep Goyal Sumit kr. Sharma

11142507

Page 2: Core Java Training report

Maharishi Markandeshwar University Page - 2 -

ACKNOWLEDGEMENT

The completion of this training work could have been possible with continued & dedicated

efforts & guidance of large number of faculty & staff members of the institute .I acknowledge

our gratitude to all of them. The acknowledgement however will be incomplete without specific

mention as follows

I wish to acknowledge my deep gratitude to Md. Danaeyal Hussan, teacher at HP Education

Services, Patna for his cooperation and guidance. I am also thankful to his Lab assistant that

provided staunch support throughout this training and helped me to complete the training

successfully

Furthermore I would also like to acknowledge with much appreciation the crucial role of our

HOD Prof. Sandeep Goyal for this encouragement & providing all the facilities in the

department

Finally, I would like to say that I am indebted to my parents for everything that they have done

for me. All of this would have been impossible without their constant support. And I also thank

to God for being kind to me and driving me through this journey.

Sumit Kumar Sharma

Page 3: Core Java Training report

Maharishi Markandeshwar University Page - 3 -

MAHARISHI MARKANDESHWAR UNIVERSITY

MULLANA, AMBALA

Department of Computer Science & Engineering

CERTIFICATE

PASTE YOUR CERTIFICATE HERE

Page 4: Core Java Training report

Maharishi Markandeshwar University Page - 4 -

MAHARISHI MARKANDESHWAR UNIVERSITY

MULLANA, AMBALA

Department of Computer Science & Engineering

APPROVAL CERTIFICATE

This dissertation work entitled “Industrial Training Report on CORE JAVA” submitted by

Mr. Sumit Kumar Sharma is approved for the award of degree of Bachelor of Technology in

Computer Science and Engineering.

Internal Examiner External Examiner

Date: Date:

Page 5: Core Java Training report

Maharishi Markandeshwar University Page - 5 -

INDEX

S. No TOPIC NAME PAGE NO. SIGN.

1. Company Profile 6

2. History of Java 7

3. Features of Java 10

4. Introduction To Java 12

5. The Java Platform 14

6. Installation Of Java 16

7. Configuring Variable 18

8. Write, Compile And Run a Java Program 20

9. Package 21

10. Class And Object 22

11. Inheritance 23

12. Variable And Method 25

13. Modifiers 28

14. Import Statement 30

15. More java Languages Constructs 31

16. IDE 40

Page 6: Core Java Training report

Maharishi Markandeshwar University Page - 6 -

COMPANY PROFILE

Hewlett Packard Enterprise has been conducting Training Program for the last 8 years with great

success in India. The Trainings is conducted by Hewlett Packard Enterprise partners. All

Trainers who conduct Training are authorized Hewlett Packard Enterprise Partner trainers. At all

locations the training is delivered by Hewlett Packard Enterprise Training Partner Professionals

only. Hewlett Packard Enterprise is in Education sector for 30 years. You get associated with

No.1 IT Company. Every Year approximately 20k students are trained in various programs

conducted by Hewlett Packard Enterprise. Qualified Hewlett Packard Enterprise Partner Trainers

with good experience deliver such trainings. Specifically Designed Programs based on Industry

requirements. We provide adequate conceptual and practical sessions. Additional Modules on

Communication Skills, G.D, and P.I will be provided, depending on the program enrolled for.

Anybody who is an Undergraduate, Graduate or Post Graduate which includes All B.Tech /

MCA , M.Sc IT, B.Sc IT , BCA , PGDCA can opt training from HP. Students studying in 1st

year to final year can undergo this program. The Training is also designed to fulfill the

requirements of the 6th semester students who wish to do Industrial Training, a mandatory part

of their curriculum. Students who wish to upgrade their existing skills can also undergo the

program. Students wanting to do International Certifications should do this program.

Page 7: Core Java Training report

Maharishi Markandeshwar University Page - 7 -

HISTORYOF JAVA

It is quite interesting to know the development of Java technology, which is widely accepted in

the area of networked/distributed computing. Java evolved from a project developing a language

for programming consumer electronic devices at Sun Microsystems, USA.

Sun’s Stealth Project in 1990 was aimed to do research in the area of application of computers in

the consumer electronics market. Bill Joy, James Gosling, Mike Sheridan, Patrick Naughton

(formerly the project leader of Sun’s Open Windows user environment), and several other

individuals discussed the ideas for the Stealth Project in January 1991.The vision of this project

was to develop smart consumer electronic devices that could all be centrally controlled and

programmed from a handheld-remote-control-like device. The Stealth group began to work to

achieve this goal. It was realized that a platform-independent development-environment was

needed.

Green Project was initiated by Patrick Naughton, Mike Sheridan, and James Gosling of Sun

Microsystems in 1991 (Members of the Stealth Project, which later became known as the Green

Project) The tasks of the project were divided amongst the members of Green Project. Mike

Sheridan concentrated on business development, Patrick Naughton worked on the graphics

system, and James Gosling was to identify the appropriate programming language for the Green

Project. Even though creating a new language was not the aim of Green Project, a new language

was created as a programming tool in this project since C++ was found unsuitable for the project.

An intelligent remote control called *7 (Star Seven) was delivered as the first product of Green

Project in 1992. It is a PDA- like device comprising of a new language oak, an operating system

called GreenOS, user interface, and hardware. This device was quite impressive to Sun

Executives. But no customer was interested in this project. The market was not conducive to this

type of device in the consumer electronics industry.

Page 8: Core Java Training report

Maharishi Markandeshwar University Page - 8 -

The new language Oak was created by James Gosling, a Green Team member, specifically for

*7. Gosling named the new language Oak because that name was struck while looking at an oak

three outside of his office window. The name Oak was later renamed to Java in order to avoid

legal issues since Oak was the name of an existing language.

In November 1992, the Green Project was incorporated under the name FirstPerson. In 1993.

Time-Warner was demanding for proposals for set-top box operating systems and video-on-

demand technology with an objective of sending the data to consumer all over the country for

display on the television sets. At the same time (1993(, NCSA released the first graphical web

browser Mosaic 1.0, an easy-to-use front end to the World Wide Web.

When FirstPerson was bidding on the Time-Warner TV trial based on video-on-demand

technology, Time-Warner chose Silicon Graphics, Inc. (SGI) over Sun. Hence, half of the

members of FirstPerson left for SGI and the remaining members continued to work at Sun.

Mosaic web browser revolutionized people’s perceptions. The remaining member of FirstPerson

returned to work on Java (Oak was renamed Java) to develop Java-based web browser.

FirstPerson was dissolved gradually. Naughton and Jonathan Payne developed WebRunner

(named after the movie Blade Runner). Later WevRunner was officially announced as the

HotJavaTM browser in 1994. This was the turning point for Java. At that time the World Wide

Web changed the face of Internet and it was winning the race on Internet.

Arthur Ban Hoff implemented the Java compiler in Java itself whereas Gosling implemented it in

C. The Java compiler, written in Java made the people to accept Java as a full-featured language.

Sun Microsystems officially announced Java environment at Sun World’95 on May 23, 1995.

Java entered into the mainstream of the Internet after a struggle for about four years. Netscape

Communications incorporated Java into its web browser Netscape Navigator. Within a decade,

Java was destined to be the most overreaching technology in the Internet. Java was not restricted

to the Internet alone. The initial goal of Sun was also achieved by using Java technology in

interactive set-top boxes, hand-held devices and other consumer electronics products.

Page 9: Core Java Training report

Maharishi Markandeshwar University Page - 9 -

Sun released the first version 1.0 of Java in 1996. Java is an object-oriented programming

language which evolved from C++. It is also a high-level programming language. The different

forms of Java versions are discussed in the next section.

Page 10: Core Java Training report

Maharishi Markandeshwar University Page - 10 -

FEATURES OF JAVA

According to Sun, Java is defined as a simple, object-oriented, distributed, interpreted, robust,

secure, architecture –neutral, portable, high performance, multithreaded, and dynamic

programming language and platform.

Java is simple because the syntax of well-known languages such as C and C++ are used with

modifications meant for simplification and improvement. It is easy to read and write Java code if

the reader is familiar with C/C++.

Almost everything in Java is centered on creating objects, manipulating the objects and making

objects work together. Only the primitive operations and data types are at the sub-object level.

Hence Java is an object-oriented programming language.

An application can be distributed in many systems which are connected together. Since

networking capability is incorporated in Java, the data/file can be sent across many systems to

run the application.

Java is robust because it is more reliable. It ensures the reliability by providing early checking

for possible errors. It eliminates error-prone constructs such as pointer. It eliminates error-prone

constructs such as pointer. It also supports runtime error handling.

Java programs are compiled to a byte code format that can be read and run by interpreters on

many platforms including Windows, Linux, etc. Hence, it is architecture neutral. Because of this

feature it is portable to new hardware and operating systems.

Page 11: Core Java Training report

Maharishi Markandeshwar University Page - 11 -

Although the speed of execution of Java programs is slower compared to C/C++ programs, Java

is meant for distributed applications. Whenever the file/data is transmitted from one system to

another, the performance is not affected. Hence, it is having high performance.

Java supports multithreaded programming to perform several tasks simultaneously. Any code

can be loaded without recompilation at runtime. Hence it is dynamic.

Page 12: Core Java Training report

Maharishi Markandeshwar University Page - 12 -

INTRODUCTION TO JAVA

With the invention of microprocessors, the world is scientifically developed with sophisticated

equipments, systems, and devices. Microprocessors are used in computers, televisions, and fax

machines. Even the hand-held devices such as pagers, PDAs (Personal Digital Assistant), and

cell phones make use of microprocessors. All these electronic devices are helpful because of

their communication capabilities. With the increasing capabilities and decreasing cost of

information processing and networking technologies, the network is growing rapidly for

transmitting information through electronic systems.

Internet is the network of networks between different types of computers located at different

places to transmit information. Information can reach to any place in the world quickly at a

cheaper rate through the Internet. Thus, the Internet has made the world a global village for

information exchange. The emerging infrastructure of electronic devices and interconnected

computer networks create an environment that presents new challenges to software industries.

for this emerging computing environment, Java process to be a well – suited programming

language. it is found suitable for networked environments involving a great variety of computer

and devices.

Java has many characteristics that have contributed to its popularity:

Platform independence - Many languages are compatible with only one platform. Java

was specifically designed so that it would run on any computer, regardless if it was

running Windows, Linux, Mac, Unix or any of the other operating systems.

Simple and easy to use - Java's creators tried to design it so code could be written

efficiently and easily.

Multi-functional - Java can produce many applications from command-line programs to

applets to Swing windows (basically, sophisticated graphical user interfaces).

Page 13: Core Java Training report

Maharishi Markandeshwar University Page - 13 -

Java does have some drawbacks. Since it has automated garbage collection, it can tend to use

more memory than other similar languages. There are often implementation differences on

different platforms, which have led to Java being described as a "write once, test everywhere"

system. Lastly, since it uses an abstract "virtual machine", a generic Java program doesn't have

access to the Native API's on a system directly. None of these issues are fatal, but it can mean

that Java isn't an appropriate choice for a particular piece of software.

Page 14: Core Java Training report

Maharishi Markandeshwar University Page - 14 -

THE JAVA PLATFORM

One thing that distinguished Java from some other languages is its ability to run the same

compiled code across multiple operating systems.In other languages, the source code (code that

is written by the programmer), is compiled by a compiler into an executable file. This file is in

machine language, and is intended for a single operating system/processor combination, so the

programmer would have to re-compile the program seperately for each new operating

system/processor combination.Java is different in that it does not compile the code directly into

machine language code. Compilation creates bytecode out of the source code. Bytecode

generally looks something like this:

a7 f4 73 5a 1b 92 7d

When the code is run by the user, it is processed by something called the Java Virtual Machine

(JVM). The JVM is essentially an interpreter for the bytecode. It goes through the bytecode and

runs it. There are different versions of the JVM that are compatible with each OS and can run the

same code. There is virtually no difference for the end-user, but this makes it a lot easier for

programmers doing software development.

Java and Open Source:-

In 2006 Sun started to make Java available under the GNU General Public License

(GPL). Oracle continues this project called OpenJDK.

Java Virtual machine :-

The Java virtual machine (JVM) is a software implementation of a computer that

executes programs like a real machine.

Page 15: Core Java Training report

Maharishi Markandeshwar University Page - 15 -

The Java virtual machine is written specifically for a specific operating system, e.g. for

Linux a special implementation is required as well as for Windows.

Java programs are compiled by the Java compiler into bytecode. The Java virtual machine

interprets this bytecode and executes the Java program.

Java Runtime Environment vs. Java Development Kit

A Java distribution comes typically in two flavors, the Java Runtime Environment (JRE)

and the Java Development Kit (JDK).

The Java runtime environment (JRE) consists of the JVM and the Java class libraries and

contains the necessary functionality to start Java programs.

The JDK contains in addition the development tools necessary to create Java programs.

The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java

class libraries.

Page 16: Core Java Training report

Maharishi Markandeshwar University Page - 16 -

INSTALLATION OF JAVA

Check installation:

Java might already be installed on your machine. You can test this by opening a console

(if you are using Windows: Win+R, enter cmd and press Enter) and by typing in the

following command:

java -version

If Java is correctly installed, you should see some information about your Java

installation. If the command line returns the information that the program could not be

found, you have to install Java.

Installing the Java Development Kit:

Before installing the Java Development Kit (JDK), you should probably know what it is.

It is distributed by Oracle. It contains the core libraries and compiler required to develop

Java. The JDK should not be confused with the JRE (Java Runtime Environment). The

JRE is a JVM for running, as opposed to compiling, Java programs.

Downloading and Installing:

To download the JDK, go to

http://www.oracle.com/technetwork/java/javase/downloads/index.html. Click on "JDK

with Net Beans Bundle". Follow the instructions for downloading the JDK installation

file.

Windows: If you are running Windows, simply run the executable file and follow the

installation instructions.

UNIX, Solaris, or Linux: For Linux and UNIX, download the "jdk1 6.0" for Linux

systems. Save the downloaded file in any drive. Once you have saved the file, extract it to

a place that you can remember, by using Terminal or by double clicking on the file.

Page 17: Core Java Training report

Maharishi Markandeshwar University Page - 17 -

When you have finished extracting the file, copy the JDK 1.6.0 folder and paste it in the

user/local (To paste to the user/local directory, you have to be in root) so that every user

can use the java files. You can delete the downloaded zip file so that it doesn't take up

space on your drive.

Macintosh: The latest available JDK is automatically installed by the operating

system. Because Java for Macintosh is developed and maintained by Apple, in

coordination with Sun, the current version on the Macintosh may not be the current

version that is available

Note on Editions:

The JDK comes in three editions.

Java Standard Edition (JSE) – This version is the basic platform for Java. The course will

focus on this edition.

Java Enterprise Edition (JEE) – This edition is mainly for developing and running

distributed multitier architecture Java applications, based largely on modular software

components running on an application server. We will not be covering this version in the

course.

Java Micro Edition (JME) – This edition is primarily for developing programs to run on

consumer appliances, such as PDAs and cell phones.

Page 18: Core Java Training report

Maharishi Markandeshwar University Page - 18 -

CONFIGURING VARIABLES

Before writing code, it is recommended that you set the Path variable on your system so

you can compile your code more easily.

For Windows Users:

From the Control Panel, double click "System" (System and Maintenance in Vista)

For Windows 7 or Vista, click on "System," "Advanced System Settings" on the left, and

then on "Environment Variables."

For XP and 2000, click on the "Advanced" tab and click on "Environment Variables" For

NT, click on the "Environment" tab.

Select the Path variable and click "Edit"

Add the path to the bin directory of where Java is installed on your hard drive. It should

probably be: C:\Program Files\Java\jdk1.6.0_20\bin unless you changed it during

installation.

Click OK

Validate installation:

Switch again to the command line and run the following command.

java -version

The output should be similar to the following output.

java version "1.7.0_25"

OpenJDK Runtime Environment (IcedTea 2.3.10) (7u25-2.3.10-1ubuntu0.13.04.2)

OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)

Page 19: Core Java Training report

Maharishi Markandeshwar University Page - 19 -

Development Process with Java:

Java source files are written as plain text documents. The programmer typically writes

Java source code in an Integrated Development Environment (IDE) for programming. An

IDE supports the programmer in the task of writing code, e.g. it provides auto-formatting

of the source code, highlighting of the important keywords, etc.

At some point the programmer (or the IDE) calls the Java compiler (javac). The Java

compiler creates the byte code instructions. These instructions are stored in .class files

and can be executed by the Java Virtual Machine.

Garbage collector

The JVM automatically re-collects the memory which is not referred to by other objects.

The java garbage collector checks all object references and find the objects which can be

automatically released.

While the garbage collector releases the programmer from the need to explicitly manage

memory the programmer still need to ensure that he does not keep unneeded object

references otherwise the garbage collector cannot release the associated memory.

Keeping unneeded object references are typically called memory leaks.

Class path

The class path defines where the Java compiler and Java runtime look for .class files to

load. This instruction can be used in the Java program.

For example if you want to use an external Java library you have to add this library to

your class path to use it in your program.

Page 20: Core Java Training report

Maharishi Markandeshwar University Page - 20 -

WRITE, COMPILE AND RUN A JAVA PROGRAM

Write source code:

Let us look at a simple code that would print the words Hello World.

public class MyFirstJavaProgram{

/* This is my first java program.

* This will print 'Hello World' as the output

*/

public static void main(String[]args){

System.out.println("Hello World");// prints Hello World

}

}

Let's look at how to save the file, compile and run the program. Please follow the steps given

below:

Open notepad and add the code as above.

Save the file as: MyFirstJavaProgram.java.

Open a command prompt window and go o the directory where you saved the class. Assume it's

C:\.

Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no

errors in your code, the command prompt will take you to the next line (Assumption: The path

variable is set).

Page 21: Core Java Training report

Maharishi Markandeshwar University Page - 21 -

BASICS: PACKAGE, CLASS AND OBJECT

It is important to understand the base terminology of Java in terms of packages, classes and

objects. This section gives an overview of these terms.

Package:

Java groups classes into functional packages.

Packages are typically used to group classes into logical units. For example all graphical views

of an application might be placed in the same package called com.vogella.webapplication.views.

It is common practice to use the reverse domain name of the company as top level package. For

example the company might own the domain, vogella.com and in this example the Java packages

of this company starts with com.vogella.

Other main reason for the usage of packages is to avoid name collisions of classes. A name

collision occurs if two programmers give the same fully qualified name to a class. The fully

qualified name of a class in Java consists out of the package name followed by a dot (.) and the

class name.

Without packages, a programmer may create a Java class called Test. Another programmer may

create a class with the same name. With the usage of packages you can tell the system which

class to call. For example if the first programmer puts the Test class into package report and the

second programmer puts his class into package xmlreader you can distinguish between these

classes by using the fully qualified name, e.g. xmlreader.Test or report.Test.

Page 22: Core Java Training report

Maharishi Markandeshwar University Page - 22 -

Class:

Def.: Template that describes the data and behavior associated with an instance of that class. In

Java source code a class is defined by the class keyword and must start with a capital letter. The

body of a class is surrounded by {}.

package test;

class MyClass {

}

The data associated with a class is stored in variables ; the behavior associated to a class or

object is implemented with methods.

A class is contained in a Java source file with the same name as the class plus the .java

extension.

Object

Def.: An object is an instance of a class.

The object is the real element which has data and can perform actions. Each object is created

based on the class definition.

Inheritance

A class can be derived from another class. In this case this class is called a subclass. Another

common phrase is that a class extends another class.

The class from which the subclass is derived is called a superclass.

Inheritance allows a class to inherit the behavior and data definitions of another class.

The following codes demonstrate how a class can extend another class. In Java a class can

extend a maximum of one class.

Page 23: Core Java Training report

Maharishi Markandeshwar University Page - 23 -

package sumit.java;

class MyBaseClass {

void hello(){

System.out.println("Hello from MyBaseClass");

}

}

package com.vogella.javaintro.base;

class MyExtensionClass extends MyBaseClass {

}

Override methods and the @override annotation

If a class extends another class it inherits the methods from its superclass. If it wants to change

these methods it can override these methods. To override a method you use the same method

signature in the source code of the subclass.

To indicate to the reader of the source code and the Java compiler that you have the intention to

override a method you can use the @override annotation.

The following code demonstrates how you can override a method from a superclass.

package sumit.java;

class MyBaseClass {

void hello(){

System.out.println("Hello from MyBaseClass");

}

}

Page 24: Core Java Training report

Maharishi Markandeshwar University Page - 24 -

package sumit.java;

class MyExtensionClass2 extends MyBaseClass {

}

Object has superclass

Every object in Java implicitly extends the Object class. The class defines the following methods

for every Java object:

equals(o1) allows to check if the current object is equal to o1

getClass() returns the class of the object

hashCode() returns an identifier of the current object

toString() Give a string representation of the current object

Page 25: Core Java Training report

Maharishi Markandeshwar University Page - 25 -

VARIABLES AND METHODS

Variable

Variables allow the Java program to store values during the runtime of the program.

A variable can either be a primitive variable or a reference variable. A primitive variable

contains value while the reference variable contains a reference (pointer) to the object. Hence if

you compare two reference variables, you compare if both point to the same object. To compare

objects use the object1.equals(object2) method call.

Instance variable

Instance variable is associated with an instance of the class (also called object). Access works

over these objects.

Instance variables can have any access control and can be marked final or transient. Instance

variables marked as final cannot be changed after assigned to a value.

Local variable

Local (stack) variable declarations cannot have access modifiers.

Final is the only modifier available to local variables. This modifier defines that the variable

cannot be changed after first assignment.

Local variables do not get default values, so they must be initialized before use.

Methods

A method is a block of code with parameters and a return value. It can be called on the object.

Page 26: Core Java Training report

Maharishi Markandeshwar University Page - 26 -

package sumit.java;

public class MyMethodExample {

void tester(String s) {

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

}

}

Method can be declared with var-args. In this case the method declares a parameter which

accepts from zero to many arguments (syntax: type .. name;) A method can only have one var-

args parameter and this must be the last parameter in the method.

Overwrite of a superclass method: A method must be of the exact same return parameter and the

same arguments. Also the return parameter must be the same. Overload methods: An overloaded

method is a method with the same name, but different arguments. The return type can not be

used to overload a method.

Main method

A public static method with the following signature can be used to start a Java application. Such

a method is typically called main method.

public static void main(String[] args){

}

Constructor

A class contains constructors that are invoked to create objects based on the class definition.

Constructor declarations look like method declarations except that they use the name of the class

and have no return type. A class can have several constructors with different parameters. Each

class must define at least one constructor.

In the following example the constructor of the class expects a parameter.

Page 27: Core Java Training report

Maharishi Markandeshwar University Page - 27 -

package sumit.java;

public class MyConstructorExample2 {

String s;

public MyConstructorExample2(String s) {

this.s = s;

}

}

If no explicit constructor is defined the compiler adds implicitly a constructor. If the class is sub-

classed then the constructor of the super class is always implicitly called in this case.

In the following example the definition of the constructor without parameters (also known as the

empty constructor) is unnecessary. If not specified the compiler would create one.

package sumit.java;

public class MyConstructorExample {

// Unnecessary, would be created by the compiler if left out

public MyConstructorExample() {

}

}

The naming conversion for creating a constructor is the following: classname

(Parameter p1, ..) {} .

Every object is created based on a constructor. This constructor method is the first statement

called before anything else can be done with the object.

Page 28: Core Java Training report

Maharishi Markandeshwar University Page - 28 -

MODIFIERS

Access modifiers

There are three access modifiers keywords available in Java. public, protected and private. There

are four access levels: public, protected, default and private. They define how the corresponding

element is visible to other components. If something is declared public, e.g. classes or methods

can be freely created or called by other Java objects. If something is declared private, e.g. a

method, it can only be accessed within the class in which it is declared. protected and default are

similar. A protected class can be accessed from the package and sub-classes outside the package

while a default class can get only accessed via the same package. The following table describes

the visibility:

Table1. Access Level

Modifier Class Package Subclass World

Public Y Y Y Y

protected Y Y Y N

no

modifier Y Y N N

Private Y N N N

Other modifiers

final methods: cannot be overwritten in a subclass

abstract method: no method body

synchronized method: threat safe, can be final and have any access control

Page 29: Core Java Training report

Maharishi Markandeshwar University Page - 29 -

native methods: platform dependent code, apply only to methods

strictfp: class or method

Page 30: Core Java Training report

Maharishi Markandeshwar University Page - 30 -

IMPORT STATEMENTS

Usage of import statements

In Java you have to access a class always via its full-qualified name, e.g. the package name and

the class name. You can add import statements for classes or packages into your class file, which

allow you to use the related classes in your code without the package qualifier.

Static imports

Static import is a feature that allows members (fields and methods) which are defined in a class

with the public static access modifier to be used in Java code without specifying the class in which

the member is defined. The feature provides a typesafe mechanism to include constants into code

without having to reference the class that originally defined the field.

Page 31: Core Java Training report

Maharishi Markandeshwar University Page - 31 -

MORE JAVA LANGUAGE CONSTRUCTS

Interface

Interfaces are contracts for what a class can do but they say nothing about the way in which the

class must do it. An interface is a type similar to a class. Like a class an interface defines

methods. An interface can have only abstract methods, no concrete methods are allowed.

Methods defined in interfaces are by default public and abstract – explicit declaration of these

modifiers is optional. Interfaces can have constants which are always implicitly public, static and

final. A class can implement an interface. In this case it must provide concrete implementations

of the interface methods. If you override a method defined by an interface you can also use the

@override annotation. The following code shows an example implementation of an interface and

its usage within a class.

package sumit.java;

public interface MyDefinition {

// constant definition

String URL="http://www.vogella.com";

// define several method stubs

void test();

void write(String s);

}

package com.vogella.javaintro.base;

public class MyClassImplementation implements MyDefinition {

Page 32: Core Java Training report

Maharishi Markandeshwar University Page - 32 -

@Override

public void test() {

// TODO Auto-generated method stub

}

@Override

public void write(String s) {

// TODO Auto-generated method stub

}

}

Class methods and class variables

Class methods and class variables are associated with the class and not an instance of the class,

i.e. objects. To refer to these element you can use the classname and a dot (".") followed by the

class method or class variable name. Class methods and class variables are declared with the

static keyword. Class methods are also called static methods and class variables are also called

static variables or static fields.

An example for the usage of a static field is println of the following statement:

System.out.println("Hello World"). out is a static field, an object of type PrintStream, and you

call the println() method on this object. If you define a static variable the Java runtime

environment associates one class variable for a class no matter how many instances (objects)

exists. The static variable can therefore be seen as a global variable. The following code

demonstrates the usage of static fields.

Page 33: Core Java Training report

Maharishi Markandeshwar University Page - 33 -

package com.vogella.javaintro.base;

public class MyStaticExample {

static String PLACEHOLDER = "TEST";

static void test() {

System.out.println("Hello");

}

}

package com.vogella.javaintro.base;

public class Tester {

public static void main(String[] args) {

System.out.println(MyStaticExample.PLACEHOLDER);

MyStaticExample.test();

}

}

If a variable should be defined as constant, you declare it with the static and the final

keyword. The static method runs without any instance of the class, it cannot directly access non-

static variables or methods.

Page 34: Core Java Training report

Maharishi Markandeshwar University Page - 34 -

ABSTRACT CLASS AND METHODS

A class and method can be declared as abstract. An abstract class can not be directly

instantiated. If a class has at least one method which only contain the declaration of the method

but not the implementation then this class is abstract and can not be instantiated. Sub-classes

need then to define the methods except if they are also declared as abstract. If a class contains an

abstract method it also needs to get defined with the keyword abstract. The following example

shows an abstract class.

package sumit.java;

public abstract class MyAbstractClass {

abstract double returnDouble(); }

Working With ClassesTable 2_

What to do How to do it

Create a new class called MyNewClass.

package test;

public class MyNewClass {

}

Create a new attribute (instance variable)

called var1 of type String in the MyNewClass

class

package test;

public class MyNewClass {

private String var1;

}

Create a Constructor for your MyNewClass package test;

Page 35: Core Java Training report

Maharishi Markandeshwar University Page - 35 -

What to do How to do it

class which has a String parameter and assigns

the value of it to the var1 instance variable.

public class MyNewClass {

private String var1;

public MyNewClass(String

para1) {

var1 = para1;

// or this.var1= para1;

}

}

Create a new method called doSomeThing in

your class which does not return a value and

has no parameters

package test;

public class MyNewClass {

private String var1;

public MyNewClass(String

para1) {

var1 = para1;

// or this.var1= para1;

}

public void doSomeThing() {

}

}

Create a new method called doSomeThing2 in

your class which does not return a value and

has two parameters, a int and a Person

package test;

public class MyNewClass {

Page 36: Core Java Training report

Maharishi Markandeshwar University Page - 36 -

What to do How to do it

private String var1;

public MyNewClass(String

para1) {

var1 = para1;

// or this.var1= para1;

}

public void doSomeThing() {

}

public void doSomeThing2(int a,

Person person) {

}

}

Create a new method called doSomeThing2 in

your class which returns an int value and has

three parameters, two Strings and a Person

package test;

public class MyNewClass {

private String var1;

public MyNewClass(String

para1) {

var1 = para1;

// or this.var1= para1;

}

Page 37: Core Java Training report

Maharishi Markandeshwar University Page - 37 -

What to do How to do it

public void doSomeThing() {

}

public void doSomeThing2(int a,

Person person) {

}

public int doSomeThing3(String

a, String b, Person person) {

return 5; // Any value will do

for this example

}

}

Create a class called MyOtherClass with two

instance variables. One will store a String, the

other will store a Dog. Create getter and setter

for these variables.

package test;

public class MyOtherClass {

String myvalue;

Dog dog;

public String getMyvalue() {

return myvalue;

}

public void setMyvalue(String

myvalue) {

this.myvalue = myvalue;

Page 38: Core Java Training report

Maharishi Markandeshwar University Page - 38 -

What to do How to do it

}

public Dog getDog() {

return dog;

}

public void setDog(Dog dog) {

this.dog = dog;

}

}

Working With Local Variable

Table 3:

What to do How to do it

Declare a (local) variable of type string. String variable1;

Declare a (local) variable of type string and assign

"Test" to it. String variable2 = "Test";

Declare a (local) variable of type Person Person person;

Declare a (local) variable of type Person, create a

new Object and assign the variable to this object. Person person = new Person();

Declare a array of type String String array[];

Declare a array of type Person and create an array

for this variable which can hold 5 Persons. Person array[]= new Person[5];

Assign 5 to the int variable var1 (which was

already declared); var1 = 5;

Page 39: Core Java Training report

Maharishi Markandeshwar University Page - 39 -

What to do How to do it

Assign the existing variable pers2 to the exiting

variable pers1; pers1 = pers2;

Declare a ArrayList variable which can hold

objects of type Person ArrayList<Person> persons;

Create a new ArrayList with objects of type

Person and assign it to the existing variable

persons

persons = new

ArrayList<Person>();

Declare a ArrayList variable which can hold

objects of type Person and create a new Object for

it.

ArrayList<Person> persons =

new ArrayList<Person>();

Page 40: Core Java Training report

Maharishi Markandeshwar University Page - 40 -

INTEGRATED DEVELOPMENT ENVIRONMENT

The previous chapter explained how to create and compile a Java program on the command line.

A Java Integrated Development Environment (IDE) provides lots of ease of use functionality for

creating java programs. There are other very powerful IDE's available, for example the Eclipse

IDE. . For an introduction on how to use the Eclipse IDE please see Eclipse IDE Tutorial. The

remaining description uses the phrase: Create a Java project called... ". This refers to creating a

Java project in Eclipse. If you are using a different IDE please follow the required steps in this

IDE. Exercises - Creating Java objects and methods Create a Person class and instantiate it

Create a new Java project called com.vogella.javastarter.exercises1 and a package with the same

name. Create a class called Person. Add three instance variables to it, one for storing the first

name of the person, on for storing the last name and one for storing the age of the Person. Use

the constructor of the Person object to set the values to some default value. Write a public

method called writeName() which uses the System.out.println( method to print the first name of

the person to the console. Create a new class called Main with a public static void main(String[]

args). In this method create an instance of the Person class.