Friday, June 14, 2019

Chapter 1 Introduction to Java

Chapter 1 Introduction to Java
Features of java:-
1. Simple
2. Object-Oriented
3. Architecture neutral
4. High Performance
5. Distributed
6. Multithreade
7. Platform independent
8. Secured
9. Robust
10. Portable
11. Dynamic
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications etc.
Platform Independent
Platform Independent
Secured
Java is secured because:
 No explicit pointer
 Java Programs run inside virtual machine sandbox
 Classloader: adds security by separating the package for the classes of the local file system from those that are imported from network sources.
 Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.
 Security Manager: determines what resources a class can access such as reading and writing to the local disk.
A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust.
Portable
We may carry the java bytecode to any platform.
Java Tool
Description
appletviewer
To run applets outside of a web browser.
jar
To aggregate and compress multiple files into a singe JAR file.
java
To launch Java applications.
javac
To compile Java source files to binary class files.
javadoc
To generate API documentation out of Java source files.
javah
To generate C language header and stubs while writing native methods.
javap
To disassemble Java class files.
java-rmi
To generate stubs, skeletons and other RMI related tasks.
jdb
To debug a Java class
rmic
To generate stubs and skeletons for Java remote objects
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc.Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
Difference between C++ and JAVA
Comparison Index
C++
Java
Platform-independent
C++ is platform-dependent.
Java is platform-independent.
Mainly used for
C++ is mainly used for system programming.
Java is mainly used for application programming. It is widely used in window, web-based, enterprise and mobile applications.
Goto
C++ supports goto statement.
Java doesn't support goto statement.
Multiple inheritance
C++ supports multiple inheritance.
Java doesn't support multiple inheritance through class. It can be achieved by interfaces in java.
Operator Overloading
C++ supports operator overloading.
Java doesn't support operator overloading.
Pointers
C++ supports pointers. You can write pointer program in C++.
Java supports pointer internally. But you can't write the pointer program in java. It means java has restricted pointer support in java.
Compiler and Interpreter
C++ uses compiler only.
Java uses compiler and interpreter both.
Call by Value and Call by reference
C++ supports both call by value and call by reference.
Java supports call by value only. There is no call by reference in java.
Structure and Union
C++ supports structures and unions.
Java doesn't support structures and unions.
Thread Support
C++ doesn't have built-in support for threads. It relies on third-party libraries for thread support.
Java has built-in thread support.
Documentation comment
C++ doesn't support documentation comment.
Java supports documentation comment (/** ... */) to create documentation for java source code.
Virtual Keyword
C++ supports virtual keyword so that we can decide whether or not override a function.
Java has no virtual keyword. We can override all non-static methods by default. In other words, non-static methods are virtual by default.
Inheritance Tree
C++ creates a new inheritance tree always.
Java uses single inheritance tree always because all classes are the child of Object class in java. Object class is the root of inheritance tree in java.
Structure of java program
Class Section: The Class section describes the information about user-defined classes present in the program. A class is a collection of fields (data variables) and methods that operate on the fields. Every program in Java consists of at least one class, the one that contains the main method. The main () method which is from where the execution of program actually starts and follow the statements in the order specified.
The class section is mandatory.
Main Method class:
Java stand alone program requires main method as starting point.
This is essential part of program
Main method creates object of various classes.
After discussing the structure of programs in Java, we shall now discuss a program that displays a string Hello Java on the screen.
// Program to display message on the screen
class HelloJava
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
A Java program consists of different sections. Some of them are mandatory but some are optional. The optional section can be excluded from the program depending upon the requirements of the programmer.
Documentation Section
It includes the comments to tell the program's purpose. It improves the readability of the program.
Package Statement
It includes statement that provides a package declaration. e.g package Student
Import statements
It includes statements used for referring classes and interfaces that are declared in other packages. e.g import java.io.*;
Interface Section
Interface like class but includes group of methods declaration .Used when we want to implement multiple inheritance feature. It is similar to a class but only includes constants, method declaration.
Data Types
Data Type
Default Value
Default size
boolean
false
1 bit
char
'\u0000'
2 byte
byte
0
1 byte
short
0
2 byte
int
0
4 byte
long
0L
8 byte
float
0.0f
4 byte
double
0.0d
8 byte
Java Naming conventions
Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method etc.
But, it is not forced to follow. So, it is known as convention not rule.
All the classes, interfaces, packages, methods and fields of java programming language are given according to java naming convention.
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code easier to read for yourself and for other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.
Name
Convention
class name
should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.
interface name
should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
method name
should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.
variable name
should start with lowercase letter e.g. firstName, orderNumber etc.
package name
should be in lowercase letter e.g. java, lang, sql, util etc.
constants name
should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
Decision Making
Decision making statement statements is also called selection statement. That is depending on the condition block need to be executed or not which is decided by condition. If the condition is "true" statement block will be executed, if condition is "false" then statement block will not be executed. In java there are three types of decision making statement.
 if
 if-else
 switch
if-then Statement
if-then is most basic statement of Decision making statement. It tells to program to execute a certain part of code only if particular condition is true.
Syntax
if(condition)
{
Statement(s)
}
e.g
class Hello
{
int a=10;
public static void main(String[] args)
{
if(a<15)
{
System.out.println("Hello good morning!");
}
}
}
if-else statement
Type Casting
Well, all casting really means is taking an Object of one particular type and “turning it into” another Object type. This process is called casting a variable. This topic is not specific to Java, as many other programming languages support casting of their variable types.
The process of converting one data type to another is called casting. Casting is often necessary when a function returns a data of type in different form then we need to perform an operation. Under certain circumstances Type conversion can be carried out automatically, in other cases it must be
In general it can be used to execute one block of statement among two blocks, in java language if and else are the keyword in java
Syntax
if(condition)
{
Statement(s)
}
else
{
Statement(s)
}
Switch Statement
The switch statement in java language is used to execute the code from multiple conditions or case. It is same like if else-if ladder statement.
A switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and string.
"forced" manually (explicitly). For example, the read() member function of the standard input stream (System.in) returns an int.
In some cases, the data type of the expression is changed automatically to the variable's data type. For example, suppose that i is an integer variable declared as follows:
int i = 10;
Even though d is a variable of type double, the following assignment is valid:
double d = i; // valid, i is converted to type double
Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Advantage of Java Array
 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.
Disadvantage of Java Array
 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Types of Array in java
There are two types of array.
 Single Dimensional Array
 Multidimensional Array
Single/One Dimensional Array in java
Syntax to Declare an Array in java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output:
10
20
70
40
50
Multidimensional array in java/Two Dimensional Array
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java
1. int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
class Testarray3
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:1 2 3
2 4 5
4 4 5
Java String
1)
In java, string is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
1. String s="ACS College";
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
Java String Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output
java
strings
example
Java String class methods
The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.
Let's see the important methods of String class.
Java String Methods
String charAt(), String compareTo(), String concat() ,String contains() ,String endsWith(), String equals() ,equalsIgnoreCase() ,String format() ,String getBytes() ,String getChars(), String indexOf() , String isEmpty(), String join(), String lastIndexOf(), String length() ,String replace() ,String replaceAll() , String startsWith() String substring(), String toCharArray(), String toLowerCase(), String toUpperCase() ,String trim() ,String valueOf().
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.
1. String s="Sachin";
2. System.out.println(s.toUpperCase());//SACHIN
3. System.out.println(s.toLowerCase());//sachin
4. System.out.println(s);//Sachin(no change in original)
Output
SACHIN
sachin
Sachin
Java String trim() method
The string trim() method eliminates white spaces before and after string.
1. String s=" Sachin ";
2. System.out.println(s);// Sachin
3. System.out.println(s.trim());//Sachin
Output
Sachin
Sachin
Java String startsWith() and endsWith() method
1. String s="Sachin";
2. System.out.println(s.startsWith("Sa"));//true
3. System.out.println(s.endsWith("n"));//true
Output
true
true
Java String charAt() method
The string charAt() method returns a character at specified index.
1. String s="Sachin";
2. System.out.println(s.charAt(0));//S
3. System.out.println(s.charAt(3));//h
Output
S
h
Java String length() method
The string length() method returns length of the string.
1. String s="Sachin";
2. System.out.println(s.length());//6
Output
6
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second sequence of character.
1. String s1="Java is a programming language. Java is a platform. Java is an Island.";
2. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"
3. System.out.println(replaceString);
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Java String valueOf() method
The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.
1. int a=10;
2. String s=String.valueOf(a);
3. System.out.println(s+10);
Output:
1010
Java StringBuffer class
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
Important Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.
Important methods of StringBuffer class
1. public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified position.
9. public int length(): is used to return the length of the string i.e. total number of characters.
10. public String substring(int beginIndex): is used to return the substring from the specified beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.
Difference between String and StringBuffer
No.
String
StringBuffer
1)
String class is immutable.
StringBuffer class is mutable.
2)
String is slow and consumes more memory when you concat too many strings because every time it creates new instance.
StringBuffer is fast and consumes less memory when you cancat strings.
3)
String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.
StringBuffer class doesn't override the equals() method of Object class.

FYBBA(CA) Semester-II Practical Lab Assignment RDBMS

1 FYBBA(CA) Semester-II Practical Lab Assignment RDBMS Q1. Consider the following entities and their relationships. Client (client_no...