+ All Categories
Home > Documents > Java tutorials

Java tutorials

Date post: 16-Apr-2017
Category:
Upload: kamaljain
View: 220 times
Download: 0 times
Share this document with a friend
49
AN INDUSTRIAL TRAINING REPORT ON “ANDROID PROGRAMMING” Submitted in the practical fulfillment for the award of Degree of Bachelor of Technology In DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING GLOBAL INSTITUTE OF TECHNOLOGY & MANAGEMENT Submitted by Kamal jain 103046 ELECTRONICS & COMMUNICATION ENGINEERING
Transcript
Page 1: Java tutorials

AN INDUSTRIAL TRAINING REPORT

ON“ANDROID PROGRAMMING”

Submitted in the practical fulfillment for the award of Degree of Bachelor of Technology

In

DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING

GLOBAL INSTITUTE OF TECHNOLOGY & MANAGEMENT

Submitted by

Kamal jain

103046

ELECTRONICS & COMMUNICATION ENGINEERING

M.D.U. UNIVERSITY, ROHTAK

Page 2: Java tutorials

DECLARATION

I hereby declare that I have completed my six weeks summer training at

CMC DWARKA,DELHI from 1st JULY 2013 to 15th AUGUST 2013 under the

guidance of Mr.PARVEEN. I have worked with full dedication during these six

weeks of training and my learning outcomes fulfill the requirements of training for

the award of degree of Btech-ECE.

KAMAL JAIN

103046

ACKNOWLEDGEMENT

Page 3: Java tutorials

The report is about the introduction of CORE JAVA, the success of this

depends largely on the encouragement and guidelines of my training

coordinator, Mr. Parveen. I take this opportunity to express my

gratitude to the people who have been instrumental in the successful

completion of this report. I thank them enough for their tremendous

support and help. I feel motivated and encouraged every time I

interacted with them. Without their encouragement and guidance this

project would not have materialized . I am grateful for their constant

support and help.

I owe a great many thanks to great many people who helped and

supported me during my completion of term paper.I would also thank

my Institution and my faculty members without whom this project

would have been a distant reality. I also extend my heartfelt thanks to

my family and well wishers.

Table of Contents

1. Organization Overview

2 . Introduction on JAVA

Page 4: Java tutorials

3. first Program in Java

4. Integrated development Environment

5. Statement

6. Working with Strings

7. Type Coversion

8. Jar files-Java Archieve

9. Reason for choosing this training

10. Learning outcomes from training

11. Bibliography

1. Organisation Overview :

CMC is a Tata Enterprise and a subsidiary of TCS (Tata Consultancy Services) is a system engineering and integration company with experience of designing and executing IT Solutions for massive, complex global projects across the value chain. CMC Academy, Education and Training arm of CMC, leverages it's vast

Page 5: Java tutorials

domain experience and focuses on providing advanced skills for employment in IT, Finance and Accounts, Design & Creative, Office Management and several other areas.

2. INTRODUCTION ON JAVA :

2.1 HISTORY :- Java is a programming language originally developed by James

Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in

1995 as a core component of Sun Microsystems' Java platform. The language derives much of

its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java

applications are typically compiled to bytecode (class file) that can run on any Java Virtual

Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent,class-

based, object-oriented language that is specifically designed to have as few implementation

dependencies as possible. It is intended to let application developers "write once, run anywhere"

Page 6: Java tutorials

(WORA), meaning that code that runs on one platform does not need to be recompiled to run on

another. Java is as of 2012 one of the most popular programming languages in use, particularly

for client-server web applications, with a reported 10 million users.

Versions:

Major release versions of Java, along with their release dates:

JDK 1.0 (January 23, 1996)

JDK 1.1 (February 19, 1997)

J2SE 1.2 (December 8, 1998)

J2SE 1.3 (May 8, 2000)

J2SE 1.4 (February 6, 2002)

J2SE 5.0 (September 30, 2004)

Java SE 6 (December 11, 2006)

Java SE 7 (July 28, 2011)

One characteristic of Java is portability, which means that computer programs written in the Java

language must run similarly on any hardware/operating-system platform. This is achieved by

compiling the Java language code to an intermediate representation called Java bytecode, instead

of directly to platform-specific machine code. Java bytecode instructions are analogous to

machine code, but are intended to be interpreted by a virtual machine (VM) written specifically

for the host hardware. End-users commonly use a Java Runtime Environment (JRE) installed on

their own machine for standalone Java applications, or in a Web browser for Java applets.

Standardized libraries provide a generic way to access host-specific features such as

graphics, threading, and networking.

A major benefit of using bytecode is porting. However, the overhead of interpretation means that

interpreted programs almost always run more slowly than programs compiled to native

executables would. Just-in-Time (JIT) compilers were introduced from an early stage that

compile bytecodes to machine code during runtime.

2.2  Overview :-

Page 7: Java tutorials

The Java programming language consists of a Java compiler, the Java virtual machine,

and the Java class libraries. The Java virtual machine (JVM) is a software

implementation of a computer that executes programs like a real machine.

The Java compiler translates Java coding into so-called byte-code. The Java virtual

machine interprets this byte-code and runs the program.

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

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

2.3. Characteristics of Java :-

The target of Java is to write a program once and then run this program on multiple

operating systems.

Java has the following properties:

Platform independent: Java programs use the Java virtual machine as

abstraction and do not access the operating system directly. This makes Java

programs highly portable. A Java program which is standard complaint and

follows certain rules can run unmodified all several platforms, e.g. Windows or

Linux.

Object-orientated programming language: Except the primitive data types, all

elements in Java are objects.

Strongly-typed programming language: Java is strongly-typed, e.g. the types of

the used variables must be pre-defined and conversion to other objects is

relatively strict, e.g. must be done in most cases by the programmer.

Interpreted and compiled language: Java source code is transfered into byte-

code which does not depend on the target platform. This byte-code will be

Page 8: Java tutorials

interpreted by the Java Virtual machine (JVM). The JVM contains a so called

Hotspot-Compiler which translates critical byte-code into native code.

Automatic memory management: Java manages the memory allocation and de-

allocation for creating new objects. The program does not have direct access to

the memory. The so-called garbage collector deletes automatically object to

which no active pointer exists.

The Java syntax is similar to C++. Java is case sensitive, e.g. the variables myValue

and myvalue will be treated as different variables.

2.4. Development with Java

The programmer writes Java source code in an text editor which supports plain text.

Normally the programmer uses an IDE (integrated development environment) for

programming. An IDE support 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 platform independent code which is called bytecode. This byte-code is

stored in ".class" files.

Bytecode can be executed by the Java runtime environment. The Java runtime

environment (JRE) is a program which knows how to run the bytecode on the operating

system. The JRE translates the bytecode into native code and executes it, e.g. the

native code for Linux is different then the native code for Windows.

By default, the compiler puts each class file in the same directory as its source file. You

can specify a separate destination directory with –d.

 Classpath:-

The classpath is the connection between the Java compiler and Java interpreter. It

defines where the compiler and interpreter look for .class files to load.

Page 9: Java tutorials

The classpath in Java defines which Java class are available for your Java program.

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

your classpath to use it in your program.

Page 10: Java tutorials

3.   first Java program :-

3.1. Write source code

Page 11: Java tutorials

The following Java program is developed under Microsoft Windows. The process on

other operating system should be similar but will not be covered here. Select a directory

which should contain your code. I will use the directory c:\temp\java which will be

called javadir.

Open a text editor which supports plain text, e.g. notepad under Windows and write the

following source code. You can start notepad via Start->Run-> notepad and pressing

enter.

// The smallest Java program possible

public class HelloWorld {

public static void main(String[] args) {

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

}

}

Save the source code in your directory "javadir" under the name "HelloWorld.java".The

name of a Java source file must always equals the class name (within the source code)

and end with .java. In our case the filename must be HelloWorld.java because the class

is called HelloWorld.

3.2. Compile and run your Java program

Page 12: Java tutorials

Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to the

"javadir" directory with the command cd javadir, for example in my case cd c:\temp\java.

Use the command dir to see that the source file is in the directory.

javac HelloWorld.java

Check the content of the directory with the command "dir". The directory contains now a

file "HelloWorld.class". If you see this file you have successfully compiled your first Java

source code into byte-code.

Run -> cmd. Switch to the directory jardir.

To run your program type in the command line:

java HelloWorld

The system should write "Hello World" on the command line.

Page 13: Java tutorials

3.3. Using the classpath

You can use the classpath to run the program from another place in your directory.

Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to any

directory you want. Type:

java HelloWorld

Page 14: Java tutorials

If you are not in the directory in which the compiled class is stored then the system

should result an error message Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass

To use the class type the following command. Replace "mydirectory" with the directory

which contains the test directory. You should again see the "HelloWorld" output.

java -classpath "mydirectory" HelloWorld

Page 15: Java tutorials

4. 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

Page 16: Java tutorials

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.

In the following I will say "Create a Java project SomeName". This will refer to creating

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

in this IDE.

Page 17: Java tutorials

5.   Statements :-

The following describes certain aspects of the software.

Page 18: Java tutorials

5.1. Boolean Operations

Use == to compare two primitives or to see if two references refers to the same object.

Use the equals() method to see if two different objects are equal.

&& and || are both Short Circuit Methods which means that they terminate once the

result of an evaluation is already clear. Example (true || ....) is always true while (false

&& ...) always false is. Usage:

(var !=null && var.method1()..) ensures that var is not null before doing the real check.

Table 1. Boolean

Operations Description

== Is equal, in case of objects the system

checks if the reference variable point

to the same object, is will not

compare the content of the objects!

&& And

!= is not equal, similar to the "=="

a.equals(b) Checks if string a equals b

a.equalsIgnoreCase(b) Checks if string a equals b while

ignoring lower cases

If (value ? false : true) {} Return true if value is not true.

Page 19: Java tutorials

Operations Description

Negotiation

5.2. Switch Statement

The switch statement can be used to handle several alternatives if they are based on

the same constant value.

switch (expression) {

case constant1:

command;

break; // Will prevent that the other cases or also executed

case constant2:

command;

break;

...

default:

}

Example:

switch (cat.getLevel()) {

Page 20: Java tutorials

case 0:

return true;

case 1:

if (cat.getLevel() == 1) {

if (cat.getName().equalsIgnoreCase(req.getCategory())) {

return true;

}

}

case 2:

if (cat.getName().equalsIgnoreCase(req.getSubCategory())) {

return true;

}

}

Page 21: Java tutorials

6.   Working with Strings :-

The following lists the most common string operations.

Page 22: Java tutorials

Table 2. 

Command Description

text1.equals("Testing"); return true if text1 is equal to "Testing". The test is case sensitive.

text1.equalsIgnoreCase("Testing"); return true if text1 is equal to "Testing". The test is not case

sensitive. For example it would also be true for "testing"

StringBuffer str1 = new StringBuffer(); Define a new String with a variable length.

str.charat(1); Return the character at position 1. (Strings starting with 0)

str.substring(1); Removes the first characters.

str.substring(1, 5); Gets the substring from the second to the fifths character.

str.indexOf(String) Find / Search for String Returns the index of the first occurrence of

the specified string.

str.lastIndexOf(String) Returns the index of the last occurrence of the specified string.

StringBuffer does not support this method. Hence first convert the

StringBuffer to String via method toString.

str.

endsWith(String)

Returns true if str ends with String

Page 23: Java tutorials

Command Description

str.startsWith(String) Returns true if str starts with String

str.trim() Removes spaces

str.replace(str1,str2) Replaces all occurrences of str1 by str2

str.concat(str1); Concatenates str1 at the end of str.

str.toLowerCase() str.toUpperCase() Converts string to lower- or uppercase

str1 + str2 Concatenate str1 and str2

String[] zeug = myString.split("-"); String[]

zeug = myString.split("\\.");

Spits myString at / into Strings. Attention: the split string is a

regular expression, so if you using special characters which have

a meaning in regular expressions you need to quote them. In the

second example the . is used and must be quoted by two

backslashes.

Page 24: Java tutorials

7. Type Conversion

If you use variables of different types Java requires for certain types an explicit

conversion. The following gives examples for this conversion.

Page 25: Java tutorials

8.1. Conversion to String

Use the following to convert from other types to Strings

// Convert from int to String

String s1 = String.valueOf (10); // "10" String s2 =

// Convert from double to String

String.valueOf (Math.PI); // "3.141592653589793"

// Convert from boolean to String

String s3 = String.valueOf (1 < 2); // "true"

// Convert from date to String

String s4 = String.valueOf (new Date()); // "Tue Jun 03 14:40:38 CEST 2003"

8.2. Conversion from String to Number

// Conversion from String to int

int i = Integer.parseInt(String);

// Conversion from float to int

float f = Float.parseFloat(String);

// Conversion from double to int

double d = Double.parseDouble(String);

The conversion from string to number is independent from the Locale settings, e.g. it is

always using the English notification for number. In this notification a correct number

format is "8.20". The German number "8,20" would result in an error.

To convert from a German number you have to use the NumberFormat class. The

challenges is that if the value is for example 98.00 then the NumberFormat class would

Page 26: Java tutorials

create a Long which cannot be casted to Double. Hence the following complex

conversion class.

private Double convertStringToDouble(String s) {

Locale l = new Locale("de", "DE");

Locale.setDefault(l);

NumberFormat nf = NumberFormat.getInstance();

Double result = 0.0;

try {

if (Class.forName("java.lang.Long").isInstance(nf.parse(s))) {

result = Double.parseDouble(String.valueOf(nf.parse(s)));

} else {

result = (Double) nf.parse(new String(s));

}

} catch (ClassNotFoundException e1) {

e1.printStackTrace();

} catch (ParseException e1) {

e1.printStackTrace();

}

return result;

}

Page 27: Java tutorials

8.3. Double to int

int i = (int) double;

8.4. SQL Date conversions

Use the following to convert a Date to a SQL date

package test;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

public class ConvertDateToSQLDate {

private void convertDateToSQL(){

SimpleDateFormat template =

new SimpleDateFormat("yyyy-MM-dd");

java.util.Date enddate =

new java.util.Date("10/31/99");

java.sql.Date sqlDate =

java.sql.Date.valueOf(template.format(enddate));

}

Page 28: Java tutorials

public static void main(String[] args) {

ConvertDateToSQLDate date = new ConvertDateToSQLDate();

date.convertDateToSQL();

}

}

Page 29: Java tutorials
Page 30: Java tutorials

8. JAR files - Java Archive

9.1. What is a jar

A JAR file is a Java Archive based on the pkzip file format. A jar files can contain java classes

and other resources (icons, property files) and can be executable.

JAR files are the deployment format for Java. You can distribute your program in a jar file or

you can use exiting java code via jars by putting them into your classpath.

9.2. Executable jar

An executable JAR means the end-user does not have to pull the class files out before running

the program. This is done via a manifest.txt file which tells the JVM which class has the main()

method. The content of the manifest.txt file:

Manifest-Version: 1.0 Main-Class: MyApp Class-Path:

. lib/jcommon-1.0.6.jar lib/itext-1.4.6.jar "Empty Line"

An empty line is required otherwise the jar won't be executable. Space after a new line is also

required

To create one executable JAR file run on the command line

jar -cvmf mainfest.txt app1.jar *.class

Page 31: Java tutorials
Page 32: Java tutorials

9. Classes :-

The following can be used as a reference for certain task which you have to do.

10.1. Working with classes

While programming Java you have to create several classes, methods, instance variables. The

following uses the package test.

Table 3. 

What to do How to do it

Create a new class calledMyNewClass.package test;

public class MyNewClass {

}

Create a new attribute (instance variable) "var1" in MyNewClass

with type Stringpackage test;

public class MyNewClass {

private String var1;

}

Create a Constructor for "MyNewClass which has a String

parameter and assigns the value of it to the "var1" instance package test;

Page 33: Java tutorials

What to do How to do it

variable.public class MyNewClass {

private String var1;

public MyNewClass(String para1) {

var1 = para1;

// or this.var1= para1;

}

}

Create a new method "doSomeThing" in class which do not

return a value and has no parameterspackage test;

public class MyNewClass {

private String var1;

public MyNewClass(String para1) {

var1 = para1;

// or this.var1= para1;

}

public void doSomeThing() {

Page 34: Java tutorials

What to do How to do it

}

}

Create a new method "doSomeThing2" in class which do not

return a value and has two parameters, a int and a Personpackage test;

public class MyNewClass {

private String var1;

public MyNewClass(String para1) {

var1 = para1;

// or this.var1= para1;

}

public void doSomeThing() {

}

public void doSomeThing2(int a, Person person) {

Page 35: Java tutorials

What to do How to do it

}

}

Create a new method "doSomeThing2" in class which do return

an int value and has three parameters, two Strings and a Personpackage test;

public class MyNewClass {

private String var1;

public MyNewClass(String para1) {

var1 = para1;

// or this.var1= para1;

}

public void doSomeThing() {

}

public void doSomeThing2(int a, Person person) {

Page 36: Java tutorials

What to do How to do it

}

public int doSomeThing3(String a, String b, Person person) {

return 5; // Any value will do for this example

}

}

Create a class "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 =

Page 37: Java tutorials

What to do How to do it

myvalue;

}

public Dog getDog() {

return dog;

}

public void setDog(Dog dog) {

this.dog = dog;

}

}

10.2. Working with local variable

A local variable must always be declared in a method.

Table 4. 

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";

Page 38: Java tutorials

What to do How to do it

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;

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 39: Java tutorials
Page 40: Java tutorials

Reason for choosing this training:-

I have choosed Java language as my training because it will help me in several ways .I

haven choosen my college course in Java and by having little bit knowledge in this

subject will help me in next semester. During learning this I came to understand much

more basic concepts of C/C++.As Java is combination of C/C++ 25% each and rest in

JAVA. Java is used now-a-day so much in every field whether it is in mobile

application ,games,offices,android etc..So it has many benifts of learning this language.

Page 41: Java tutorials

Learning Outcome from training :-

General learning outcomes:

An understanding of the principles and practice of object oriented analysis and design in the

construction of robust, maintainable programs which satisfy their requirements;

A competence to design, write, compile, test and execute straightforward programs using a

high level language;

An appreciation of the principles of object oriented programming;

An awareness of the need for a professional approach to design and the importance of good

documentation to the finished programs.

Specific learning outcomes:

Be able to implement, compile, test and run Java programmes, comprising more than one

class, to address a particular software problem.

Understand how to include arithmetic operators and constants in a Java program.

Be able to make use of members of classes found in the Java API (such as the Math class).

Demonstrate the ability to employ various types of selection constructs in a Java program.

Be able to employ a hierarchy of Java classes to provide a solution to a given set of

requirements.

Demonstrate the ability to employ repetition constructs in a Java program.

Bibliography

Page 42: Java tutorials

Books :- The Complete Reference Java2 fifth edition

(by:- Herbert Schildt)

JAVA BOOK BY BALAGURUSWAMY 

References:-

www.tutorialspoint.com/java/index.htm

http://www.oracle.com/technetwork/java/index

www.allschoolstuff.com


Recommended