Professional Documents
Culture Documents
(June-July, 2012)
CORE JAVA
Submitted by
SAHIL CHOPRA Registration Number : 10901966 Programme Name : BTECH-CSE CourseCode : CSE443
CSE Discipline School of Technology and Sciences Lovely Professional University, Phagwara
DECLARATION
I hereby declare that I have completed my six weeks summer training at APTECH JALANDHAR from 1st JUNE 2012 to 15th JULY 2012 under the guidance of Mr.NEERAJ TONDON. 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-CSE, Lovely Professional University, Phagwara.
Date:4-Aug-2012
ACKNOWLEDGEMENT
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. NEERAJ TONDON. 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.
SAHIL CHOPRA
Table of Contents 1. Organization Overview 2 . Introduction on JAVA 3. Your first Program in Java 4. Integrated development Environment 5. Your first graphical interface application (GUI) 6. Statement 7. Working with Strings 8. Type Coversion 9. Jar files-Java Archieve 10. Reason for choosing this training 11. Learning outcomes from training 12. Bibliography
1. Organisation Overview :
APTECH commenced its education and training business in 1986 and has globally trained over 6.4 million students. Aptech is an ISO 9001:2000 organization and the first IT Training and Education company to get this certification for Education Support Services in 1993. Aptech has presence in more than 40+ emerging countries through its two main streams of businesses Individual training and Enterprise Business. As a leader in career education, it has over 1305 centres of learning across the world. Under Individual Training, Aptech offers career and professional training through its Aptech Computer Education, Arena Animation & Maya Academy of Advanced Cinematics (both in Animation & Multimedia), Aptech Hardware & Networking Academy, Aptech Aviation & Hospitality Academy and Aptech English Learning Academy brands. Enterprise business includes Content Development (Aptech Learning Services), Training and Assessment Solutions for Corporates & Institutions (Aptech Training Solutions, Aptech Assessment & Testing Solutions). Aptech is associated with "Project Saraswati" for IT Literacy and "Project Srishti" for Multimedia Training. Under these two projects, Aptech provides free-of-cost training to underprivileged children at various Aptech and Arena centres. Aptechs N-Power Hardware & Networking training brand, meanwhile, conducts training for deaf children. Arena organizes Graphic Designing and Personality Development programs for underprivileged children. Aptech Computer Education, the flagship brand of Aptech Ltd., has entered into an alliance with Middlesex University to provide advance entry to students doing Aptech Certified Computer Professional (ACCP) course in the final year of B.Sc. (Honors) at their London, Dubai or Mauritius Campus.
1.2 LOCATION :-
Java Technologies : J2EE,EJB,JSP,J2ME,Servlet,Struts,Spring,Hibernate,Tapestry,Web Services,XML.SOAP. Microsoft Technologies : .Net Framework,ASP.net,VB.Net,C#.net,Web Services,SQL Services,DOT NET (DNN). Databases : Oracle 10g,Microsoft sql server,Db2,MySQL. PHP Technologies : PHP ,Java script,joomla,Cake PHP. Operating System : Windows 7,Windows 8,XP,Linux,Solaris. Mobile Technologies : MS Windows Mobile,J2ME,iphone,Google Android.
APTECH has a team with expertise in diverse domains of Mobile app development in iPhone, Mobile app development in Android, Mobile app development in Symbian, MultiCore Processor programming, Emerging Embedded systems ARM cortext A8, JAVA app development, .NET programming and many more. Our motto is to deliver Quality and Excellence. APTECH team has a global exposure of IT industry. Their team has been giving technical trainings and consultancy to companies located in USA. Experts travelled worldwide and have vast exposure. Their Students placed in Infosys, RBS , Sanyo, Aricent and many more MNCs Alumni .They have IT industry experts with more than 13 years of experience . APTECH is a Software Development Company.. Specialist in 6 weeks/6 months training for engineers/MCA students. Aurtorised training partner of ORACLE,MICROSOFT,RED HAT and SUN MICROSYSTEMS. APTECHs Industrial training programs are designed according to the industry needs . Original Certificate and courseware directly from parent companies lke of ORACLE,MICROSOFT,RED HAT and SUN MICROSYSTEMS etc. More than 50 qualified and certified trainers with experience in software development. Guest lecturers by Industry Experts. Industrial Training Certificate from Software Development Company. World class infrastructurewith licensed softwares. Classroom training includes Audio-Visual aid,Wi-Fi labs. Interview Preparation and Personality development program. Dedicated placement cell with 100% placements. Seminars on advanced technologies for ORACLE,MICROSOFT,RED HAT and SUN MICROSYSTEMS etc.
2. INTRODUCTION ON JAVA :
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 :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 bytecode which does not depend on the target platform. This byte-code will be 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 deallocation 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.
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. 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.
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.
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
java HelloWorld
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
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 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.
import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField;
public MyFirstUI() {
// Lets make it look nice // This you can ignore / delete if you do not like it // try {
// for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (Exception e) { // e.printStackTrace(); // }
// create and attach buttons // create a label and add it to the main window
JLabel firstNamelabel = new JLabel(" Firstname: "); pane.add(firstNamelabel);
JLabel lastNamelabel = new JLabel(" Lastname: "); pane.add(lastNamelabel); lastName = new JTextField(); pane.add(lastName);
// Pack will make the size of window fitting to the compoents // You could also use for example setSize(300, 400);
pack();
private class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (!checkbox.isSelected()) { JOptionPane.showMessageDialog(null, "I do not like you, " + firstName.getText() + " " + lastName.getText() + "!"); } else { JOptionPane.showMessageDialog(null, "How are you, " + firstName.getText() + " " + lastName.getText() + "?"); } }
} }
Create also the following class MainTester.java in package test and start this class.
package test;
import ui.MyFirstUI;
public class MainTester { public static void main(String[] args) { MyFirstUI view = new MyFirstUI(); view.setVisible(true); } }
You should see the following. A mesage dialog should be seen if you press the button.
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
!=
a.equals(b)
a.equalsIgnoreCase(b)
Negotiation
Example:
7. Working with Strings :The following lists the most common string operations. Table 2.
Command
Description
text1.equals("Testing");
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"
Command
Description
str.charat(1);
str.substring(1);
str.substring(1, 5);
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)
str.startsWith(String)
str.trim()
Removes spaces
str.replace(str1,str2)
str.concat(str1);
Command
Description
str.toLowerCase() str.toUpperCase()
str1 + str2
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.
8. Type Conversion
If you use variables of different types Java requires for certain types an explicit conversion. The following gives examples for this conversion.
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 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; }
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));
} public static void main(String[] args) { ConvertDateToSQLDate date = new ConvertDateToSQLDate(); date.convertDateToSQL(); }
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
10. Classes :The following can be used as a reference for certain task which you have to do.
What to do
How to do it
What to do
How to do it
// or this.var1= para1;
} }
// or this.var1= para1;
}
What to do
How to do it
// or this.var1= para1;
}
What to do
How to do it
an int value and has three parameters, two Strings and a Person
public class MyNewClass { private String var1;
// or this.var1= para1;
}
public int doSomeThing3(String a, String b, Person person) { return 5; // Any value will do for this example
What to do
How to do it
will store a String, the other will store a Dog. Create getter and setter for these variables.
public class MyOtherClass { String myvalue; Dog dog;
What to do
How to do it
What to do
How to do it
String variable1;
Person person;
Declare a (local) variable of type Person, create a new Object and assign the variable to this object.
What to do
How to do it
String array[];
Declare a array of type Person and create an array for this variable which can hold 5 Persons.
var1 = 5;
pers1 = pers2;
ArrayList<Person> persons;
Create a new ArrayList with objects of type Person and assign it to the existing variable persons
Declare a ArrayList variable which can hold objects of type Person and create a new Object for it.
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.
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.
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.
Bibliography
Books : The Complete Reference Java2 fifth edition (by:- Herbert Schildt) JAVA BOOK BY BALAGURUSWAMY