0% found this document useful (0 votes)
123 views44 pages

Day 1 Java Fundamentals PDF

Uploaded by

Vikash Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views44 pages

Day 1 Java Fundamentals PDF

Uploaded by

Vikash Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

ra

E d
IT hin
EL Ma
Introduction to Java
ch
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 1


Objectives
At the end of this session, you will be able to

ra
 Download and install Java

E d
 Understand the Java architecture

IT hin
 Compile and run Java applications
 Understand the language fundamentals

EL Ma
 Use the control structures in programs
 Use arrays and strings
ch
 Write programs using command line arguments
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 2


Agenda

 Introduction to Java

ra
 Java Architecture

E d
 Setting up the environment

IT hin
 Language Fundamentals
 Data types and operators

EL Ma
 Control Structures
 Arrays and Strings
ch
 Command line arguments
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 3


Introduction to Java
 Java is :
• A Programming language
• A development environment

ra
• A deployment environment

E d
IT hin
 Similar in syntax to C++; similar in semantics to Smalltalk

EL Ma
 Operating system independent ch
 Runs on Java Virtual Machine (JVM)
Te

 A secure operating environment that runs as a layer on top of the OS


 A sandbox which protects the OS from malicious code

 Object Oriented Programming language


 In Java, everything is a class

Copyright © 2013 Tech Mahindra. All rights reserved. 4


Features of Java
 Object oriented
 Simple

ra
Robust

E d
Architecture neutral

IT hin
 Portable

EL Ma
Secure
 High performance ch
 Interpreted

Te

Support for Multi-threading


 Distributed

Copyright © 2013 Tech Mahindra. All rights reserved. 5


Platform Independence
 A platform is the hardware & software environment in which a program runs

ra
 Once compiled, java code runs on any platform without recompiling or any

E d
kind of modification

IT hin
“Write Once Run Anywhere”

EL Ma
 Java Virtual Machine (JVM) made this possible
ch
Te

CONFIDENTIAL© Copyright 2008 Tech 6


Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 6
Java 2 Platform

ra
E d
IT hin
EL Ma
ch
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 7


Assembly Language
LDA #47
STA $570
DEX

ra
JSR $817

E d
CPX #0
Translation

IT hin
BNE #14
program 00010100
(Assembler)

EL Ma
Assembly language program 001100101
00001000
100100101
ch
010101010
Te

10010
Machine language program
(executable file)

Copyright © 2013 Tech Mahindra. All rights reserved. 8


C Language

#include <stdio.h>

ra
0001010000

E d
1100101000

IT hin
main() 0100010010
{ C Compiler 01010101010

EL Ma
printf(“Hallo”); 1010010
}
ch
Te

Machine language program


C Program (executable “.exe” file)

Copyright © 2013 Tech Mahindra. All rights reserved. 9


Java Architecture
JVM

Class Loader

ra
Source File (HelloWorld.java)

E d
IT hin
Byte Code Verifier

EL Ma
JIT Code
ch
Compiler (javac) Interpreter
Generator
Te

Runtime

Byte code
(HelloWorld.class) Operating System

Hardware
CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 101
0
Write Once Run Anywhere!
public class Hello{
public static void main(String[] args){
System.out.println("Hello World!");
}

ra
}
Hello.java

E d
IT hin
javac (java compiler)

EL Ma
Interpreter Interpreter Interpreter Interpreter
ch
Te

Bytecode (Class)

Hello.class

Write Once Run Anywhere ! Web Server


Copyright © 2013 Tech Mahindra. All rights reserved. 11
Java Compiler
 Translates java code into platform independent byte codes

 The byte code will be in a file with extension .class

ra
E d
IT hin
 Byte code is in binary language to be interpreted by JVM

EL Ma
 Also performs strong type checking, prevents access violations etc.
ch
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 12


Java Virtual Machine
 JVM makes Java platform independent

 Reads and executes compiled byte codes

ra
 Is implemented as software and is specific to each platform

E d
IT hin
 The JVM interprets the .class file to the machine language of the underlying

EL Ma
platform
ch
 The underlying platform then processes the commands given by the JVM
Te

 JVM provides definitions for the


• Instruction set (CPU)
• Class file format
• Stack
• Garbage-collection
• Memory management
Copyright © 2013 Tech Mahindra. All rights reserved. 13
Development and Execution Infrastructure

File Name: 2. Compile It


“Foo.java”
1. Write a Program
Source files
Compiler

ra
(Java Language)
Class Foo{

E d
.

IT hin
.
…main(..){ Virtual 3. Execute It

EL Ma
}
} Machine
Linux
ch
Intermediate
Te

Files(Intermediate Language) Virtual


Input Machine Output
Mac OS X
File Name
“Foo.class” Virtual
Machine
Windows
Copyright © 2013 Tech Mahindra. All rights reserved. 14
Just-In-Time Compiler (JIT)
 Converts a part of the byte code to native code.

 Requires more memory because both byte code and the corresponding native

ra
E d
code are in memory at the same time.

IT hin
EL Ma
ch
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 15


Java SE Platform Versions
Version Name Code Name Release Date

ra
JDK 1.0 Oak January 1996

E d
JDK 1.1 (none) February 1997

IT hin
J2SE 1.2 Playground December 1998

EL Ma
J2SE 1.3 Kestrel May 2000
J2SE 1.4 Merlin February 2002
ch
J2SE 5.0 Tiger September 2004
Te

Java SE 6 Mustang December 2006


Java SE 7 Dolphin July 2011
Java SE 8 (Not available) March 2014

Copyright © 2013 Tech Mahindra. All rights reserved. 16


Java SE Development Kit (JDK)
 Allows programmers to create, compile, and execute Java programs on a
particular platform

ra
 Includes the command-line Java compiler (javac) and the Java Runtime

E d
IT hin
Environment (JRE)

EL Ma
 The JRE provides the runnable Java platform which supplies the java
command needed to execute Java applications
ch
 Download and install JDK 7 from
Te

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Copyright © 2013 Tech Mahindra. All rights reserved. 17


Environment Variables
 JAVA_HOME: Java Installation Directory

Windows set JAVA_HOME=C:\jdk1.7.0_51

ra
UNIX export JAVA_HOME=/var/usr/java

E d
IT hin
 CLASSPATH: Used to locate class files

EL Ma
set CLASSPATH=%CLASSPATH%;%JAVA_HOME%\lib\tools.jar
ch
Windows
Te

UNIX set CLASSPATH=$CLASSPATH:$JAVA_HOME/lib/tools.jar

 PATH: Used by OS to locate executable files

Windows set PATH=%PATH%;%JAVA_HOME%\bin

UNIX set PATH=$PATH:$JAVA_HOME/bin

Copyright © 2013 Tech Mahindra. All rights reserved. 18


Hello World Program
 Type the source code using any text editor
 Save this as Hello.java

ra
class Hello {

E d
IT hin
public static void main(String[] args) {

EL Ma
System.out.println(“Hello World”);
ch
}
Te

}
 Compilation:
C:\> javac Hello.java
 Running your first java program:
C:\> java Hello
Copyright © 2013 Tech Mahindra. All rights reserved. 19
Try it out
1. The Java compiler for Windows and Linux are same (True/False)

2. The JVM for Windows and Linux are same. (True/False)

ra
E d
3. Java compiler translates .java source files into ___________?

IT hin
a) .exe file b) .bat file c) .doc file d) .class file

EL Ma
4. _________ converts the bytecode to native code.
a) JRE b) JVM c) JIT d) JDK
ch
Te

5. Which statement is used to compile a source code file HelloJava.java?.


a) C:\> java HelloJava.java b) C:\> javac HelloJava
c) C:\> javac HelloJava.java d) C:\> javac Hello.Java.java

Copyright © 2013 Tech Mahindra. All rights reserved. 20


ra
E d
IT hin
Java Language Fundamentals
EL Ma
ch
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 21


Comments
 A single line comment starts with //
// This is a single line comment in Java

ra
E d
A multi line comment starts with /* and ends with */

IT hin
/* This is a

EL Ma
Multi line
Comment in Java */
ch
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 22


Keywords
abstract continue for new switch

assert default goto* package synchronized

ra
E d
boolean do if private this

IT hin
break double implements protected throw

EL Ma
byte else import public throws

case enum
ch instanceof return transient
Te

catch extends int short try

char final interface static void

class finally long strictfp volatile

const* float native super while

* Keywords not in use now


Copyright © 2013 Tech Mahindra. All rights reserved. 23
Identifiers & Literals
 An identifier (name) must begin with a letter, a dollar sign ($) or an underscore
character (_). Subsequent characters may be letters, $, _ or digits.

ra
 Classes, methods and variables cannot have Java Keywords as Identifiers

E d
IT hin
(names).

EL Ma
 true, false and null are literals (not keywords), but they can’t be used as
ch
identifiers as well.
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 24


Variables
 A named storage location in the computer’s memory that stores a value of a
particular type for use by program.

ra
 Example :

E d
int myAge=28, cellPhone;

IT hin
double salary;
char tempChar;

EL Ma
 Variables can be declared anywhere in the program
ch
for (int count=0; count < max; count++) {
int z = count * 10;
Te

 If a local variable is used without initializing, the compiler will show an error.
The below is an error
int tempVal;
System.out.println(tempVal);

CONFIDENTIAL© Copyright 2008 Tech


Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 25
Data Types
 The Data type can either be:

 Built-in primitive type

ra
 Holds value

E d
IT hin
 Reference data type

EL Ma
 Holds reference to objects

 Example
ch
int primitive = 5;
Te

String reference = “Hello” ;

 Memory Representation
primitive 5

reference Hello
CONFIDENTIAL© Copyright 2008 Tech 26
Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 26
Primitive Data Types
Data Size Type Signed Default Min Value Max Value
Type (bits) Value

boolean 1 N/A N/A false false True

ra
char 16 Single  ‘\u0000’ ‘\u0000’ (0) ‘\uFFFF’ (216 – 1)

E d
Unicode

IT hin
Character
byte 8 Integer  0 -128(-27) 127 (27 – 1)

EL Ma
short 16 Integer  0 -215 215 – 1
 -231 231 – 1
int 32 Integer
ch 0
long 64 Integer  0L -263 263 – 1
Te

float 32 Floating  0.0F 1.4E-45 3.4028235E38


Point
Number
double 64 Floating  0.0 4.9E-324 1.7976931348623157
Point E308
Number

Append uppercase or lowercase "L" or "F" to the number to specify a long or a float number.
Copyright © 2013 Tech Mahindra. All rights reserved. 27
Unicode Character Set
 char data type in Java is 2 bytes because it uses UNICODE character set
to support internationalization

ra
E d
 UNICODE character set supports all known scripts and languages in the

IT hin
world

EL Ma
ch
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 28


Operators
Type of Operators Operators Associativity
Postfix operators [] . (parameters) ++ -- Left to Right
Prefix Unary operators ++ -- + - ~ ! Right to Left

ra
Object creation and cast new (type) Right to Left

E d
Multiplication/Division/Modulus */% Left to Right

IT hin
Addition/Subtraction +- Left to Right
Shift >> >>> << Left to Right

EL Ma
Relational < <= > >= instanceof Left to Right
Equality == != Left to Right
ch
Bit-wise/Boolean AND & Left to Right
Te

Bit-wise/Boolean XOR ^ Left to Right


Bit-wise/Boolean OR | Left to Right
Logical AND (Short-circuit or && Left to Right
Conditional)
Logical OR (Short-circuit or || Left to Right
Conditional)
Ternary ?: Right to Left
Assignment = += -= *= /= %= <<= >>= >>>= &= ^= |= Right to Left
Copyright © 2013 Tech Mahindra. All rights reserved. 29
Conversions and Casting
 Automatic type changing is known as Implicit Conversion

 A variable of smaller capacity can be assigned to another variable of

ra
bigger capacity. This is called widening
int i = 10;

E d
double d;

IT hin
d = i;

EL Ma
 Legal conversions are
byte  short  int  long  float  double
ch

Te

char

 Whenever a larger type is converted to a smaller type, we have to explicitly


specify the type cast operator as narrowing is not allowed

double d = 10
Type cast operator
int i;
i = (int) d;
Copyright © 2013 Tech Mahindra. All rights reserved. 30
Control Structures
 Work the same as in C / C++
if/else, for, while, do/while, switch

ra
E d
IT hin
EL Ma
ch
Te

CONFIDENTIAL© Copyright 2008 Tech 31


Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 31
Flow Control Statements
 Java supports continue & break keywords

 A break statement will cause the current iteration of the innermost loop to stop

ra
and the next line of code following the loop to be executed.

E d
IT hin
 A continue statement will cause the current iteration of the innermost loop to

EL Ma
stop, and the condition of that loop to be checked, and if the condition is met,
perform the loop again. ch
Te

CONFIDENTIAL© Copyright 2008 Tech 32


Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 32
Arrays
 An ordered collection of homogeneous data elements
 Size to be specified at compile time and is static – cannot be modified
 Arrays in Java are objects and can be of primitive data type or reference type

ra
E d
 The length property on arrays tells the size of the array

IT hin
EL Ma
An array holding 5 int elements
22 33 66 100 72
ch
Te

An array holding 4 Car objects

Reference to Car Object

CONFIDENTIAL© Copyright 2008 Tech 33


Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 33
Arrays
 Arrays should be
Declared
int[] a; String b[]; Object []c;

ra
Allocated (constructed)

E d
IT hin
a = new int[10];
b = new String[arraysize]

EL Ma
Initialized
for (int i = 0; i < a.length; a[i++] = 0)
ch
Te

 An array can also be initialized while it is declared as follows:


int [] x = {1, 2, 3, 4};

char [] c = {‘a’, ‘b’, ‘c’};

 Unlike C, Java checks the boundary of an array while accessing an element in it


CONFIDENTIAL© Copyright 2008 Tech 34
Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 34
Multidimensional Arrays
 A Multi-dimensional array is an array of arrays

ra
 To declare a multidimensional array, specify each additional index using

E d
another set of square brackets

IT hin
int [][] x;

EL Ma
//x is a reference to an array of int arrays
ch
x = new int[3][4];
//Create 3 new int arrays, each having 4 elements
Te

//x[0] refers to the first int array, x[1] to the second and so on
//x[0][0] is the first element of the first array
//x.length will be 3
//x[0].length, x[1].length and x[2].length will be 4

CONFIDENTIAL© Copyright 2008 Tech 35


Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 35
Strings
 An object of the String class represents a fixed length, immutable sequence of
unicode characters

ra
 All String operations (concat, trim, replace, substring etc) construct and return

E d
new strings.

IT hin
 String objects are immutable. If modified, Java creates a new object having

EL Ma
the modified character sequence
ch
String myName = “Elliot Koffman”;
myName = “Koffman, Elliot”;
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 36


Strings
public class StringDemo {

public static void main(String args[]){

ra
E d
char letter = 'a';

IT hin
String string1 = "Hello"; // String literals are stored as String objects

EL Ma
String string2 = "World";
String string3 = "";
ch
String dontDoThis = new String ("Bad Practice"); // Use is discouraged
Te

string3 = string1 + string2; // + is to concatenate strings

System.out.println("Output: " + string3 + " " + letter);

}
}

Copyright © 2013 Tech Mahindra. All rights reserved. 37


String Operations
public class StringOperations {
public static void main(String arg[]){
String string2 = "World";

ra
String string3 = "";

E d
IT hin
string3 = "Hello".concat(string2);
System.out.println("string3: " + string3);

EL Ma
// Get length
ch
System.out.println("Length: " + string1.length());
Te

// Get SubString
System.out.println("Sub: " + string3.substring(0, 5));

// Uppercase
System.out.println("Upper: " + string3.toUpperCase());
}
}
Copyright © 2013 Tech Mahindra. All rights reserved. 38
Arrays and for-each loop
public class ArrayOperations {
public static void main(String args[]){

ra
String[] names = new String[3];

E d
IT hin
names[0] = "Blue Shirt";
names[1] = "Red Shirt";

EL Ma
names[2] = "Black Shirt";
ch
int[] numbers = {100, 200, 300};
Te

for (String name:names){


System.out.println("Name: " + name);
}

for (int number:numbers){


System.out.println("Number: " + number);
}
}
}
Copyright © 2013 Tech Mahindra. All rights reserved. 39
Command Line Arguments
 Information that follows program’s name on the command line when it is
executed

ra
 This data is passed to the application in the form of String arguments

E d
IT hin
class Echo {
public static void main (String args[]) {

EL Ma
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
ch
}
}
Te

C:\> java Echo Drink Hot Java


Drink
Hot
Java

CONFIDENTIAL© Copyright 2008 Tech 40


Mahindra Limited
Copyright © 2013 Tech Mahindra. All rights reserved. 40
Try it out
1. Which of the following conversions are legal?
a) byte to int b) int to char c) float to double d) double to int

ra
2. Array index starts at ___. Index is of ____ data type.

E d
a) 1,int b) null, char c) 0,int

IT hin
EL Ma
3. Java supports pointer arithmetic. (True/False)

4. Which of the below is a legal identifier?


ch
a) _a b) –a c) 7g d) my Name
Te

5. Will the below code compile?


int[5] scores;

6. Local variables get default values if not initialized. (True/False)

Copyright © 2013 Tech Mahindra. All rights reserved. 41


Summary

 In this session, we have covered:

ra
 Java2 platform and its components

E d
IT hin
 Java language fundamentals
 Identifiers & Literals

EL Ma
 Primitive Data Types & their Conversion
ch
 Operators & basic flow controls in java
 Arrays & Strings
Te

 Command line arguments

Copyright © 2013 Tech Mahindra. All rights reserved. 42


Thank you

ra
Visit us at www.techmahindra.com

E d
IT hin
EL Ma
Disclaimer
Tech Mahindra Lim ited, herein referred to as TechM provide a w ide array of presentations and reports, w ith the
ch
contributions of various professionals. These presentations and reports are for inform ational purposes and private
circulation only and do not constitute an offer to buy or sell any securities mentioned therein. They do not purport to be a
com plete description of the m arkets conditions or developm ents referred to in the m aterial. While utm ost care has been
Te
taken in preparing the above, we claim no responsibility for their accuracy. We shall not be liable for any direct or indirect
losses arising from the use thereof and the viewers are requested to use the inform ation contained herein at their ow n risk.
These presentations and reports should not be reproduced, re-circulated, published in any media, website or otherw ise, in
any form or m anner, in part or as a whole, w ithout the express consent in writing of TechM or its subsidiaries. Any
unauthorized use, disclosure or public dissem ination of inform ation contained herein is prohibited. Unless specifically
noted, TechM is not responsible for the content of these presentations and/or the opinions of the presenters. Individual
situations and local practices and standards m ay vary, so viewers and others utilizing inform ation contained w ithin a
presentation are free to adopt differing standards and approaches as they see fit. You m ay not repackage or sell the
presentation. Products and names mentioned in m aterials or presentations are the property of their respective ow ners and
the mention of them does not constitute an endorsement by TechM. Inform ation contained in a presentation hosted or
prom oted by TechM is provided “as is” w ithout w arranty of any kind, either expressed or im plied, including any w arranty of
merchantability or fitness for a particular purpose. TechM assumes no liability or responsibility for the contents of a
presentation or the opinions expressed by the presenters. All expressions of opinion are subject to change w ithout notice.

Copyright © 2013 Tech Mahindra. All rights reserved. 43


ra
E d
IT hin
EL Ma
ch
Te

Copyright © 2013 Tech Mahindra. All rights reserved. 44

You might also like