You are on page 1of 23

Introduction to Java – Day 1

Java

Introduction to JAVA – Day 1

Version: 1.0
Last Modified On: Jun 02 / 2016

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

Table of Contents
1. INTRODUCTION TO JAVA .................................................................................................. 4
1.1. What is Java .................................................................................................................................... 4

1.2. Java Overview ................................................................................................................................. 4

1.3. Features of Java .............................................................................................................................. 4

2. JAVA SETTINGS (ENVIRONMENT SETUP)........................................................................ 6


3. JAVA ARCHITECTURE ....................................................................................................... 7
3.1. Java SE or J2SE Run time Environment ........................................................................................... 7

4. TOKENS ............................................................................................................................... 8
4.1. Tokens used in Java Programs ........................................................................................................ 8

4.2. Keywords in Java............................................................................................................................. 8

4.3. Identifiers in Java ............................................................................................................................ 9

4.4. Literals in Java ............................................................................................................................... 10

4.5. Operators in Java .......................................................................................................................... 11

4.5.1. Arithmetic Operators ........................................................................................................ 11

4.5.2. Relational Operators ......................................................................................................... 11

4.5.3. Logical Operators .............................................................................................................. 11

4.5.4. Assignment Operators ...................................................................................................... 11

4.5.5. Increment and decrement Operators............................................................................... 12

4.5.6. Conditional Operators ...................................................................................................... 12

4.5.7. Bitwise Operators ............................................................................................................. 12

4.5.8. Special Operators .............................................................................................................. 12

4.6. Separators in Java ......................................................................................................................... 13

5. RECAP SESSION:.............................................................................................................. 14
5.1. Access Modifiers ........................................................................................................................... 14

5.2. Packages ....................................................................................................................................... 15

5.3. Class, Variables, Methods & Objects ............................................................................................ 16

5.3.1. Java – Objects & Classes ................................................................................................... 16

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

6. STRING HANDLING ........................................................................................................... 17


6.1. What is String in java .................................................................................................................... 17

6.2. How to create String object? ........................................................................................................ 18

6.2.1. String Literal ...................................................................................................................... 18

6.2.2. By new keyword................................................................................................................ 19

6.2.3. Java String class methods ................................................................................................. 20

7. HANDS ON / WORKING WITH PROGRAMS ..................................................................... 23


8. INTRODUCTION TO ENHANCEMENT OF MINI PROJECT .............................................. 23

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

1. INTRODUCTION TO JAVA

Overview of Java Virtual Machine

Java Virtual Machine (JVM) specification defines the JVM as an imaginary (virtual) machine
that is implemented by emulating it in software on a real machine. Code for the JVM is
stored in .class files, each of which contains code for at most one public class.

The specification enables the Java language to be platform independent.

JVM is implemented in a Java technology development tool or in a Web browser.

1.1. What is Java


Java is a high-level programming language originally developed by Sun Microsystems and
released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.

Java is a development environment that provides tools such as compiler, interpreter,


documentation generator, and so on.

Java is an application environment to run standalone programs that run on any machine
where the Java Runtime Environment (JRE) is installed.

Java is a deployment environment that supplies Java2 Software Development Kit (J2SDK)
with complete set of Application Programming Interface (APIs) as packages.

Java provides an easy-to-use language by avoiding pitfalls of other languages, such as pointer
arithmetic and memory management, which affect the robustness of the code.

1.2. Java Overview


The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java
and its widespread popularity, multiple configurations were built to suite various types of
platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.

The new J2 versions were renamed as Java SE, Java EE and Java ME respectively. Java is
guaranteed to be Write Once, Run Anywhere.

1.3. Features of Java


Java is:

 Object Oriented: In Java, everything is an Object. Java can be easily extended


since it is based on the Object model.
 Platform independent: Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

 Simple: Java is designed to be easy to learn. If you understand the basic concept of
OOP Java would be easy to master.
 Secure: With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
 Architectural-neutral: Java compiler generates an architecture-neutral object file
format which makes the compiled code to be executable on many processors, with
the presence of Java runtime system.
 Portable: Being architectural-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in ANSI
C with a clean portability boundary which is a POSIX subset.
 Robust: Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
 Multithreaded: With Java's multithreaded feature it is possible to write programs
that can do many tasks simultaneously. This design feature allows developers to
construct smoothly running interactive applications.
 Interpreted: Java byte code is translated on the fly to native machine instructions
and is not stored anywhere. The development process is more rapid and analytical
since the linking is an incremental and light weight process.
 High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
 Distributed: Java is designed for the distributed environment of the internet.
 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment. Java programs can carry extensive amount of
run-time information that can be used to verify and resolve accesses to objects on
run-time.

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

2. JAVA SETTINGS (ENVIRONMENT SETUP)

Setting up the path for windows:

Assuming you have installed Java in c:\Program Files\java\jdk directory:

 Right-click on 'My Computer' and select 'Properties'.


 Click on the 'Environment variables' button under the 'Advanced' tab.
 Now, alter the 'Path' variable so that it also contains the path to the Java executable.
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your
path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

3. JAVA ARCHITECTURE

3.1. Java SE or J2SE Run time Environment


J2SE stands for Java 2 Standard Edition. From Java SDK API version 1.5 onwards, this is
referred to as Java SE (Java Standard Edition).

The JRE provides the libraries, JVM, Java Interpreter, and other components necessarily for
you to run applets and applications written in Java.

JRE is responsible for loading, verifying, and executing the bytecodes.

The JDK includes the JRE as well as command-line development tools, such as compilers
and debuggers that are necessary or useful for developing applets and applications.

The Java API is a code that is written earlier, organized into packages of similar topics, and
it is a part of JDK libraries.

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

4. TOKENS

4.1. Tokens used in Java Programs

Reserved Keywords, Identifiers, Literals, Operators, Separators


A Java program is basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements. Most statements contain
expressions, which describe the actions carried out on data. Smallest individual unit in a
program are known as tokens. The compiler recognizes them for building up expressions
and statements.

Java Character Set


The smallest units of Java language are the characters used to write Java tokens. These
characters are defined by the Unicode character set, and emerging standard that tries to
create characters for a large number of scripts worldwide.
The Unicode is a 16-bit character coding system and currently supports more than 34,000
defined characters derived from 24 languages from America, Europe, Middle East, Africa and
Asia. However, most of us use only the basic ASCII characters, which include letters, digits
and punctuation marks, used in normal English. We therefore, have used only ASCII character
set (a subset of UNICODE character set) in developing the programs.

Java language includes five types of tokens and they are:

 Reserved Keywords

 Identifiers

 Literals

 Operators

 Separators

4.2. Keywords in Java

Java language has reserved 49 words as keywords.


Java Keywords also called a reserved word. Keywords are identifiers that Java reserves for its
own use. These identifiers have built-in meanings that cannot change. Thus, programmers
cannot use these identifiers for anything other than their built-in meanings. Technically, Java
classifies identifiers and keywords as separate categories of tokens. Keywords are an essential
part of a language definition. There are 49 reserved keywords currently defined in the Java
language and they are shown in the below table.

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

abstract double int switch

assert else interface synchronized

boolean extends long this

break false native throw

byte final new transient

case finally package true

catch float private try

char for protected void

class goto public volatile

const if return while

continue implements short

default import static

do instanceof super

The keywords const and goto are reserved but not used. In the early days of Java, several
other keywords were reserved for possible future use.

4.3. Identifiers in Java


Identifiers are programmer-designed tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a program. Java identifier’s basic rules
are as follows:

1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.

Identifier must be meaningful, short enough to be quickly and easily typed and long enough
to be descriptive and easily read. Java developers have followed some naming conventions.

 Names of all public methods and instance variables start with a leading lowercase
letter.

Example:
average
sum
9

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

 When more than one word are used in a name, the second and subsequent words
are marked with a leading uppercase letters.

Example:
dayTemperature
firstDayOfMonth
totalMarks

 All private and local variables use only lowercase letters combined with underscores.

Example:
length
Batch_strength

 All classes and interfaces start with a leading uppercase letter(and each subsequent
word with a leading uppercase letter).

Example:
Student
HelloJava
Vehicle
MotorCycle

 Variables that represent constant values use all uppercase letters and underscores
between words.

Example:
TOTAL
F_MAX
PRINCIPAL_AMOUNT
We may follow our own conventions as long as we do not break the basic rules of naming
identifiers.
The following table shows some valid and invalid identifiers:

Valid Invalid
HelloWorld Hello World (uses a space)
Hi_JAVA Hi JAVA! (uses a space and punctuation mark)
value3 3value(begins with a number)
Tall short (this is a Java keyword)
#age (does not begin with any other symbol except _ $
$age
)

It is standard Java practice to name multiple-word identifiers in lowercase except for the
beginning letter of words in the middle of the name.

4.4. Literals in Java


A literal is the source code representation of a fixed value.

10

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

Literals in Java are a sequence of characters (digits, letters, and other characters) that
represent constant values to be stored in variables. Java language specifies five major types
of literals. Literals can be any number, text, or other information that represents a value.
This means what you type is what you get. We will use literals in addition to variables in
Java statement. While writing a source code as a character sequence, we can specify any
value as a literal such as an integer.
They are:

 Integer literals
 Floating literals
 Character literals
 String literals
 Boolean literals

4.5. Operators in Java


Operators are special symbols that perform specific operations on one, two, or
three operands, and then return a result. Java supports a rich set of operators. Some of
them are =, +, -, *. An Operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations. Operators are used in programs to manipulate data
and variables. They usually form a part of mathematical or logical expressions.
Java operators can be classified into a number of related categories as below:

Arithmetic Operators
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

Relational Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

Logical Operators

&& Logical AND


|| Logical OR
! Logical NOT

Assignment Operators
= Assignment

11

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

Increment and decrement Operators

++ Adds 1 to the Operand


-- Subtracts 1 from the Operand

Conditional Operators
?: Ternary (shorthand for if-then-else statement)

Bitwise Operators
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

Special Operators
. (Dot Operator) - To access instance variables
instanceof - Object reference Operator

As we explore the operators of the Java programming language, it may be helpful for you to
know ahead of time which operators have the highest precedence. The operators in the
following table are listed according to precedence order. The closer to the top of the table an
operator appears, the higher its precedence. Operators with higher precedence are evaluated
before operators with relatively lower precedence. Operators on the same line have equal
precedence. When operators of equal precedence appear in the same expression, a rule must
govern which is evaluated first. All binary operators except for the assignment operators are
evaluated from left to right; assignment operators are evaluated right to left.

Operator Precedence

Operators Precedence

postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative */%

additive +-

shift << >> >>>

relational < > <= >= instanceof

equality == !=

12

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ?:

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

The basic evaluation procedure includes two left-to-right passes through the expression.
During the first pass, the high priority operators (if any) are applied as they are
encountered. During the second pass, the low priority operators (if any) are applied as they
are encountered.

4.6. Separators in Java


Separators help define the structure of a program. The separators used in HelloWorld are
parentheses, ( ), braces, { }, the period, ., and the semicolon, ;. The table lists the six Java
separators (nine if you count opening and closing separators as two). Following are the
some characters which are generally used as the separators in Java.

Separator Name Use


. Period It is used to separate the package name from
sub-package name & class name. It is also used
to separate variable or method from its object or
instance.
, Comma It is used to separate the consecutive parameters
in the method definition. It is also used to
separate the consecutive variables of same type
while declaration.
; Semicolon It is used to terminate the statement in Java.
() Parenthesis This holds the list of parameters in method
definition. Also used in control statements & type
casting.
{} Braces This is used to define the block/scope of code,
class, methods.
[] Brackets It is used in array declaration.
Separators in Java

13

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

5. RECAP SESSION:

5.1. Access Modifiers


Java – Modifier

Modifiers are keywords that you add to those definitions to change their meanings. The Java
language has a wide variety of modifiers, including the following:

 Java Access Modifiers


 Non Access Modifiers

To use a modifier, you include its keyword in the definition of a class, method, or variable.
The modifier precedes the rest of the statement, as in the following examples (Italic ones) –

public class className {


// ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
// body of method
}
Access Control Modifiers:

Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:

 Visible to the package, the default. No modifiers are needed.


 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).

Non Access Modifiers:

Java provides a number of non-access modifiers to achieve many other functionality.

 The static modifier for creating class methods and variables


 The final modifier for finalizing the implementations of classes, methods, and
variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.

14

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

5.2. Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier,
etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations


and annotations) providing access protection and name space management.

Some of the existing packages in Java are:

 java.lang - bundles the fundamental classes

 java.io - classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is
a good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names
in other packages. Using packages, it is easier to provide access control and it is also easier
to locate the related classes.

Creating a package:

While creating a package, you should choose a name for the package and include a
package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.

The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be placed in the current default package.

To compile the Java programs with package statements you have to do use -d option as
shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder

15

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

5.3. Class, Variables, Methods & Objects

Java – Objects & Classes


When we consider a Java program it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods and instance variables mean.

 Object - Objects have states and behaviours. Example: A dog has states - colour,
name, breed as well as behaviours -wagging, barking, and eating. An object is an
instance of a class.
 Class - A class can be defined as a template/ blue print that describes the
behaviours/states that object of its type support.
 Methods - A method is basically a behaviour. A class can contain many methods. It
is in methods where the logics are written, data is manipulated and all the actions
are executed.

Example

public class Puppy{


public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}}

A class can contain any of the following variable types.

 Local variables: Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.
 Instance variables: Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.

Class variables: Class variables are variables declared with in a class, outside any method,
with the static keyword.

16

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

6. STRING HANDLING

6.1. What is String in java


Generally, string is a sequence of characters. But in java, string is an object that represents
a sequence of characters. String class is used to create string object.

Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.

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:

String s="javatpoint";

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

17

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

6.2. How to create String object?

There are two ways to create String object:

1. By string literal
2. By new keyword

String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance is returned. If string
doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:

String s1="Welcome";

String s2="Welcome";//will not create new instance

In the above example only one object will be created. Firstly JVM will not find any string
object with the value "Welcome" in string constant pool, so it will create a new object. After
that it will find the string with the value "Welcome" in the pool, it will not create new object
but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as string
constant pool.

Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists
already in string constant pool).

18

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

By new keyword
String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal(non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).

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);
}}

19

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

Java String class methods


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.

No. Method Description

1 char charAt(int index) returns char value for the particular index

2 int length() returns string length

3 static String format returns formatted string

(String format, Object... args)

4 static String format returns formatted string with given locale

(Locale l, String format, Object... args)

5 String substring returns substring for given begin index

(int beginIndex)

6 String substring returns substring for given begin index

(int beginIndex, int endIndex) and end index

7 boolean contains(CharSequence s) returns true or false after matching the

sequence of char value

8 static String join returns a joined string

(CharSequence delimiter,
CharSequence... elements)

9 static String join returns a joined string

(CharSequence delimiter, Iterable<?


extends CharSequence> elements)

20

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

10 boolean equals(Object another) checks the equality of string with object

11 boolean isEmpty() checks if string is empty

12 String concat(String str) concatenates specified string

13 String replace(char old, char new) replaces all occurrences of specified char value

14 String replace replaces all occurrences of specified


CharSequence
(CharSequence old, CharSequence new)

15 String trim() returns trimmed string omitting leading


and trailing spaces

16 String split(String regex) returns splitted string matching regex

17 String split(String regex, int limit) returns splitted string matching regex and limit

18 String intern() returns interned string

19 int indexOf(int ch) returns specified char value index

20 int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index

21 int indexOf(String substring) returns specified substring index

22 int indexOf returns specified substring index starting with


given index
(String substring, int fromIndex)

23 String toLowerCase() returns string in lowercase.

24 String toLowerCase(Locale l) returns string in lowercase using specified locale.

25 String toUpperCase() returns string in uppercase.

21

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

26 String toUpperCase(Locale l) returns string in uppercase using specified locale.

22

Cognizant Proprietary Information – CONFIDENTIAL


Introduction to Java – Day 1

7. HANDS ON / WORKING WITH PROGRAMS

1. Create a class with 4 methods named Add, Substract, Multiply and Divide and a main calss to
work on these operations. Create object and play around by passing numbers as arguments.
2. Take the above program and change the modifiers to understand the features of modifiers.
3. Write a program to reverse a string.
4. Program to find the position of a char in a given string and its number of occurances.
5. Write a program to get a substring from given string, without using inbuilt functions.
6. Write a program to check the existence of a word in the given sentence.
7. Program to Print a palindrome and check wheather the given string is a palindrome or not. Using
srting variable.
8. Same above program with a method name palindrome accept a string and return a boolean
value to main method.
9. Write a program to calculate the age by entering DOB.
10. Program to print Ascending andDescending order.
11. Program to print Astrix prymid.
12. Write a program to reverse a number without using built in functions.

8. INTRODUCTION TO ENHANCEMENT OF MINI PROJECT

A. The Mini project has to enhanced on the below features,


1. Insertion should be at any position.
2. Deletion should be at any position.

23

Cognizant Proprietary Information – CONFIDENTIAL

You might also like