Java Programming - Lecture notes 1 PDF

Title Java Programming - Lecture notes 1
Course B.sc(Computer Science)
Institution Thiruvalluvar University
Pages 168
File Size 7.6 MB
File Type PDF
Total Downloads 104
Total Views 144

Summary

Thiruvalluvar university notes...


Description

JAVA PROGRAMMING Prepared By R.CHERAN M.sc[Computer Science] Government Arts and Science College C.multur, Chidambaram.

Syllabus Unit – I: BASICS, ESSENTIALS, CONTROL STATEMENT AND CLASSES & OBJECTS Computer and its Languages – Stage, Origin and Features for Java - JDK–OOP; Java Essentials: Program – API - Variables& Literals - Data Types - String Class – Operators - Type conversion - Constants - Scope – Comments - Keyboard Input; Control Statements: Conditional Statements – Looping Statements - Break and Continue Statements; Classes and Objects: Modifiers - Arguments - Constructors Packages and import - Static Class - Overloaded Methods and Constructors Returning Objects – to String() - this reference –Enumeration - Garbage Collection. Unit – II: ARRAYS, INHERITANCE, INTERFACES AND PACKAGES Arrays - Three or More Dimensions; Inheritance: Basics - Calling the Super class Constructor - Overriding Super class Methods - Inheritance from Subclasses – Polymorphism -Abstract Classes and Methods - Interfaces: Fields - Multiple inheritance - Interface inheritance; Packages: Creating packages – Accessing package from other packages- Access Specifier. Unit – III: STRING HANDLING, EXCEPTION HANDLING AND MULTI THREADING String Handling: Basics - Operations –String Methods - String Buffer class - String Builder – to String method -String Tokenizer class. Exception Basics: try and catch block - Multiple catch block - Nested try - throws keyword - Throw vs Throws Final Vs Finally Vs Finalize - Method Overriding - Custom Exception Multithreading: Life Cycle - Methods in Thread - thread application – Thread priority – Synchronization - Inter-thread communication - Suspending, Resuming, and Stopping Threads; Unit – IV: APPLET AND GUI APPLICATION Applets: Basis - Lifecycle - Applet classes - Application – Graphics; AWT-I: GUI Programming - AWT classes - Windows fundamentals- Creating Windows Dialog Boxes - Layout Managers - Radio Buttons and Check Boxes – BordersSwing Unit – V: JAVA DATABASE CONNECTIVITY JDBC - Types of Drivers- Architecture- Classes and Interfaces - Developing JDBC Application - New Database and Table with JDBC - Working with Database Metadata.

UNIT-I Computer and its Languages Java is a general-purpose computer programming language that is concurrent, class-based, objectoriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers “write once, run anywhere” (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. For example, you can write and compile a Java program on UNIX and run it on Microsoft Windows, Macintosh, or UNIX machine without any modifications to the source code. WORA is achieved by compiling a Java program into an intermediate language called byte code. The format of byte code is platform-independent. A virtual machine, called the Java Virtual Machine (JVM), is used to run the byte code on each platform.

History of Java Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by 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 it has fewer low-level facilities than either of them. Oracle Corporation is the current owner of the official implementation of the Java SE platform, following their acquisition of Sun Microsystems on January 27, 2010. This implementation is based on the original implementation of Java by Sun. The Oracle implementation is available for Microsoft Windows, Mac OS X, Linux and Solaris. The Oracle implementation is packaged into two different distributions: Java Runtime Environment (JRE) which contains the parts of the Java SE platform required to run Java programs and is intended for end users. Java Development Kit (JDK) which is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger.

Stage/phases of java Java program normally go through five phases. These are

    

Edit Compile Load Verify Execute

We look over all the above mentioned phases in a bit detail. First consider the following figure that summarizes the all phases of a java program.

Phase 1: Edit Phase 1 consists of editing a file. This is accomplished with an editor program. The programmer types a java program using the editor like notepad, and make corrections if necessary.

When the programmer specifies that the file in the editor should be saved, the program is stored on a secondary storage device such as a disk. Java program file name ends with a .java extension. On Windows platform, notepad is a simp le and commonly used editor for the beginners. However java integrated development environments (IDEs) such as NetBeans, Borland JBuilder, JCreator and IBM‟s Ecllipse hava built- in editors that are smoothly integrated into the programming environment.

Phase 2: Compile In Phase 2, the programmer gives the command javac to compile the program. The java compiler translates the java program into bytecodes, which is the language understood by the java interpreter. To compile a program called Welcome.java, type javac Welcome.java at the command window of your system. If the program compiles correctly, a file called Welcome.class is produced. This is the file containing the bytecodes that will be interpredted during the execution phase.

Phase 3: Loading In phase 3, the program must first be placed in memory before it can be executed. This is done by the class loader, which takes the .class file (or files) containing the bytecodes and transfers it to memory. The .class file can be loaded from a disk on yo ur system or over a network (such as your local university or company network or even the internet). Applications (Programs) are loaded into memory and executed using the java interpreter via the command java. When executing a Java application called Welcome, the command Java Welcome Invokes the interpreter for the Welcome application and causes the class loader to load information used in the Welcome program.

Phase 4: Verify Before the bytecodes in an application are executed by the java interpreter, they are verified by the bytecode verifier in Phase 4. This ensures that the bytecodes for class that are loaded form the internet (referred to as downloaded classes) are valid and that they do not violate Java‟s security restrictions. Java enforces strong security because java programs arriving over the network should not be able to cause damage to your files and your system (as computer viruses might).

Phase 5: Execute Finally in phase 5, the computer, under the control of its CPU, interprets the program one bytecode at a time. Thus performing the actions specified by the program. Programs may not work on the first try. Each of the preceding phases can fail because of various errors. This would cause the java program to print an error message. The programmer would return to the edit phase, make the necessary corrections and proceed through the remaining phases again to determine id the corrections work properly.

Java Features:  Secure  Simple  Portable  Object-oriented  Robust  Interpreted  Multithreaded  High performance  Architecture-neutral  Dynamic  Distributed

Secure  Java is secure because it is using Applet. When Applet is running, it not allowing access to other parts of the computer.  There is no pointer in Java. It does not allow direct memory access that secures Java program from unauthorized access.

Simple  If you have programming experience, then it is easy to learn Java language.  Java is based on object oriented concepts. It is similar to C++  Most programmers know C++ language. They can lean Java language easily.

Portable     

Java code is capable of running various types of machines. Java achieves its portability with help of 'Bytecode'. Java compiler converts java program into a intermediate language which called 'Bytecode'. Bytecode are then executed by Java virtual machine (JVM). Bytecode makes java code portable for various types of machines.

Object-oriented    

Java is object oriented language. It consists of classes and objects. Java program starts from the class. It advocates that java object oriented language. Java has many pre-defined classes that facilitates easy programming in the java. Java has features of object-oriented such as Polymorphism, Inheritance, Encapsulation, Abstraction and Data hiding.

Robust  Java provides reliable software. It provides two main features for producing reliable software.  Memory Management:- It provides automatic memory management. Memory allocation and deallocation are handled by java.  Exception Handling:- Java provides 'try..catch' feature to handle run-time exceptions.

Interpreted First, java source file is compiled by java compiler. Java compiler coverts java source code into bytecode which is an intermediate language. Then bytecode is interpreted by JVM (Java virtual machine). In few cases, bytecode is compiled by JIT (Just-In-Time) compiler.

Multithreaded  A thread is a piece of program that can run simultaneously with other parts of the program.  Java provides this facility to programmer.  A program can be written with multiple threads and each thread is running simultaneously other threads.  Using multithreading, Java supports multiprogramming and multitasking.

High performance Java bytecode can be easily translated directly into machine code by JVM (Java Virtual Machine)/ JIT (Just-In-Time). It gives high performance to Java code.

Architecture-neutral Goal of java language is “Write once, run anywhere". Java Virtual Machine (JVM) accomplishes this task. Therefore, java is architectural-neutral

Dynamic Java is able to access objects at run-time.

Distributed Java also supports Remote Method Invocation (RMI). It allows access of a method from anywhere. You may call method from the network.

JDK: Java Development Kit JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle corporation:  Standard Edition Java Platform  Enterprise Edition Java Platform  Micro Edition Java Platform The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) etc. to complete the development of a Java Application.

Components of JDK Following is a list of primary components of JDK: appletviewer:

This tool is used to run and debug Java applets without a web browser.

apt:

It is an annotation-processing tool.

extcheck:

it is a utility that detects JAR file conflicts.

idlj:

An IDL-to-Java compiler. This utility generates Java bindings from a given Java IDL file.

jabswitch:

It is a Java Access Bridge. Exposes assistive technologies on Microsoft Windows systems.

java:

The loader for Java applications. This tool is an interpreter and can interpret the class files generated by the javac compiler. Now a single launcher is used for both development and deployment. The old deployment launcher, jre, no longer comes with Sun JDK, and instead it has been replaced by this new java loader.

javac:

It specifies the Java compiler, which converts source code into Java bytecode.

javadoc:

The documentation generator, which automatically generates documentation from source code comments

jar:

The specifies the archiver, which packages related class libraries into a single JAR file. This tool also helps manage JAR files.

javafxpackager:

It is a tool to package and sign JavaFX applications.

jarsigner:

the jar signing and verification tool.

javah:

the C header and stub generator, used to write native methods.

javap:

the class file disassembler.

javaws:

the Java Web Start launcher for JNLP applications.

JConsole:

Java Monitoring and Management Console.

jdb:

the debugger.

jhat:

Java Heap Analysis Tool (experimental).

jinfo:

This utility gets configuration information from a running Java process or crash dump.

jmap:

Oracle jmap - Memory Map- This utility outputs the memory map for Java and can print shared object memory maps or heap memory details of a given process or core dump.

jmc:

Java Mission Control

jps:

Java Virtual Machine Process Status Tool lists the instrumented HotSpot Java Virtual Machines (JVMs) on the target system.

jrunscript:

Java command-line script shell.

jstack:

It is a utility that prints Java stack traces of Java threads (experimental).

jstat:

Java Virtual Machine statistics monitoring tool (experimental).

jstatd:

jstat daemon (experimental).

keytool:

It is a tool for manipulating the keystore.

pack200:

JAR compression tool.

Policytool:

It specifies the policy creation and management tool, which can determine policy for a Java runtime, specifying which permissions are available for code from various sources.

VisualVM:

It is a visual tool integrating several command-line JDK tools and lightweight [clarification needed] performance and memory profiling capabilities

wsimport:

It generates portable JAX-WS artifacts for invoking a web service.

xjc:

It is the part of the Java API for XML Binding (JAXB) API. It accepts an XML schema and generates Java classes.

Object Oriented Programming features:

These four features are the main OOPs Concepts that you must learn to understand the Object Oriented Programming in Java

Abstraction: Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. For example, when you login to your bank account online, you enter your user_id and password and press login, what happens when you press login, how the input data sent to server, how it gets verified is all abstracted away from the you. Read more about it here: Abstraction in Java.

Encapsulation: Encapsulation simply means binding object state(fields) and behavior(methods) together. If you are creating class, you are doing encapsulation. Encapsulation example in Java How to 1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class. 2) Have getter and setter methods in the class to set and get the values of the fields. class EmployeeCount { private int numOfEmployees = 0; public void setNoOfEmployees (int count) { numOfEmployees = count; } public double getNoOfEmployees () { return numOfEmployees; } } public class EncapsulationExample { public static void main(String args[]) { EmployeeCount obj = new EmployeeCount (); obj.setNoOfEmployees(5613); System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees()); }

} Output: No Of Employees: 5613 The class EncapsulationExample that is using the Object of class EmployeeCount will not able to get the NoOfEmployees directly. It has to use the setter and getter methods of the same class to set and get the value. So what is the benefit of encapsulation in java programming Well, at some point of time, if you want to change the implementation details of the class EmployeeCount, you can freely do so without affecting the classes that are using it.

Inheritance: The process by which one class acquires the properties and functionalities of another class is called inheritance. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it, rest of the features can be inherited from the parent class. Inheritance is a process of defining a new class based on an existing class by extending its common data members and methods. Inheritance allows us to reuse of code, it improves reusability in your java application. The parent class is called the base class or super class. The child class that extends the base class is called the derived class or sub class or child class. Note: The biggest advantage of Inheritance is that the code in base class need not be rewritten in the child class. The variables and methods of the base class can be used in the child class as well. Syntax: Inheritance in Java To inherit a class we use extends keyword. Here class A is child class and class B is parent class. class A extends B { } Inheritance Example In this example, we have a parent class Teacher and a child class MathTeacher. In the MathTeacher class we need not to write the same code which is already present in the present class. Here we have college name, designation and does() method that is common for all the teachers, thus

MathTeacher class does not need to write this code, the common data members and methods can inherited from the Teacher class. class Teacher { String designation = "Teacher"; String college = "Beginnersbook"; void does(){ System.out.println("Teaching"); } } public class MathTeacher extends Teacher{ String mainSubject = "Maths"; public static void main(String args[]){ MathTeacher obj = new MathTeacher(); System.out.println(obj.college); System.out.println(obj.designation); System.out.println(obj.mainSubject); obj.does(); } } Output: Beginnersbook Teacher Maths Teaching Note: Multi-level inheritance is allowed in Java but not multiple inheritance

Types of Inheritance: Single Inheritance: refers to a child and parent class relationship where a class extends the another class. Multilevel inheritance: refers to a child and parent class relationship where a class extends the child class. For example class A extends class B and class B extends class C.

Hierarchical inheritance: refers to a child and parent class relationship where more than one classes extends the same class. For example, class B extends class A and class C extends class A. Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a child class has two parent classes. Java doesn‟t support multiple inheritance, read more about it here. Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.

Polymorphism: Polymorphism is a object oriented programming feature that allows us to perform a single action in different ways. For example, lets say we have a class Animal that has a method animalSound(), here we cannot give implementation to this method as we do not know which Animal class would extend Animal class. So, we make this method abstract like this: public abstract class Animal{ ... public abstract void animalSound(); } Now suppose we have two Animal classes Dog and Lion that extends Animal class. We can provide the implementation detail there. public class Lion extends Animal{ ... @Override public void animalSound(){ System.out.println("Roar"); } } and public class Dog extends Animal{ ... @Override public void animalSound(){ System.out.println("Woof"); } } As you can see that although we had the common action for all subclasses animalSound() but the...


Similar Free PDFs