Date post: | 28-Jan-2016 |
Category: |
Documents |
Upload: | aaditya-kiran |
View: | 226 times |
Download: | 0 times |
Java Tutorial
SESSION - I
JAVA BASICS
April 22, 2023
Contents• JAVA Overview
• OOPS Concepts in Java
• Class Fundamentals
• Classes
• Principles of OOP
• Simple Class and Method
• Methods
• Public/private
• Using objects
• Primitive Types and Variables
• Initialisation
• Declarations
• Assignment
• Basic Mathematical Operators
• Statements & Blocks
• Flow of Control
• If – The Conditional Statement
• Relational Operators
• If… else
• Nested if … else
• else if
• The Switch Statement
• The for loop
• while loops
• Continue
• Constructors
April 22, 2023
Java – Overview
• Java is:
– platform independent programming language
– similar to C++ in syntax
• Java has some interesting features:
– automatic garbage collection,
– simplifies pointers; no directly accessible pointer to memory,
– multi-threading!
April 22, 2023
Windows LinuxSolaris
JVM(win) JVM(Sol) JVM(Lin)
Java Prog Java Prog Java Prog
XXX
JVM(XXX)
Java Prog
Platform Dependent JVM and Platform Independent Program
April 22, 2023
How it works…!
Source Code
Create/Modify Source Code
Compile Source Code i.e. javac Welcome.java
Bytecode
Run Byteode i.e. java Welcome
Result
If compilation errors
If runtime errors or incorrect result
•Java Compiler converts Java Source code to intermediate instruction set called ‘byte’ code.
•‘byte’ code is instruction set to a virtual machines called JVM – Java Virtual Machine
•JVM will convert byte instruction to underlying machine instruction during run time i.e. when program is running.
•Thus byte code remains platform independent and JVM is platform specific.
April 22, 2023
Object-Oriented Programming
• Java supports OOD
– Encapsulation
– Polymorphism
– Inheritance
• Java programs contain nothing but definitions and instantiations of
classes
– Everything is encapsulated in a class!
April 22, 2023
Principles of OOP• Encapsulation
– Objects hide their functions (methods) and data (instance variables)
• Inheritance
– Each subclass inherits all variables of its superclass
• Polymorphism
– Interface same despite different data types
car
auto-maticmanual
Super class
Subclasses
draw() draw()
April 22, 2023
Classes
• OOP - object oriented programming code built from objects are
called classes
• Each class definition is coded in a separate .java file
• Name of the object must match the class/object name
April 22, 2023
Simple Class and Method
• A class typically has two parts ‘data’ and ‘action’.
• Data – is represented by variables within the class.
• Action – represented by methods (functions in C). Methods manipulate data.
• Thus class typically encapsulates data and methods.
April 22, 2023
Using objects
• Here, code in one class creates an instance of another class and does
something with it …
Fruit plum=new Fruit();
int cals;
cals = plum.total_calories();
• Dot operator allows you to access (public) data/methods inside Fruit
class
April 22, 2023
Methods
• A method is a named sequence of code that can be invoked by other
Java code.
• A method takes some parameters, performs some computations and
then optionally returns a value (or object).
• Methods can be used as part of an expression statement.
public float convertCelsius(float tempC)
{
return( ((tempC * 9.0f) / 5.0f) + 32.0 );
}
April 22, 2023
Simple class
Class Fruit{
int grams;
int cals_per_gram;
int total_calories() {
return(grams*cals_per_gram);
}
}
April 22, 2023
Primitive Types and Variables
• Boolean, char, byte, short, int, long, float, double etc.
• These basic (or primitive) types are the only types that are not objects.
This means that you don’t use the new operator to create a primitive
variable.
• Declaring primitive variables:
float a;
int b, index = 2;
double c = 1.2;
boolean valueOk = false;
April 22, 2023
Initialisation
• If no value is assigned prior to use, then the compiler will give an
error
• Java sets primitive variables to zero or false in the case of a boolean
variable
• All object references are initially set to null
• An array of anything is an object
– Set to null on declaration
– Elements to zero false or null on creation
April 22, 2023
Declarations
int a = 1.2; // compiler error
boolean b = 1; // compiler error
double c = 5 / 4; // no error!
float d = 5.8f; // correct
double e = 5.0 / 4.0; // correct
• 1.2f is a float value accurate to 7 decimal places.
• 1.2 is a double value accurate to 15 decimal places.
April 22, 2023
Assignment
• All Java assignments are right associative
int a = 1, b = 2, c = 5
a = b = c
System.out.print(“a= “ + a + “b= “ + b + “c= “ + c)
• What is the value of a, b & c
• Done right to left: a = (b = c);
April 22, 2023
Basic Mathematical Operators
• * / % + - are the mathematical operators
• * / % have a higher precedence than + or -
double myVal = a + b % d – c * d / b;
• Is the same as:
double myVal = (a + (b % d)) – ((c * d) / b);
April 22, 2023
Relational Operators
== Equal (careful)
!= Not equal
>= Greater than or equal
<= Less than or equal
> Greater than
< Less than
April 22, 2023
Statements & Blocks
• A simple statement is a command terminated by a semi-colon:
name = “Tina”;
• A block is a compound statement enclosed in curly brackets:
{
name1 = “Tina”; name2 = “Mehta”;
}
• Blocks may contain other blocks
April 22, 2023
Flow of Control
• Java executes one statement after the other in the order they are
written
• Many Java statements are flow control statements:
Alternation: if, if else, switch
Looping: for, while, do while
Escapes: break, continue, return
April 22, 2023
If – The Conditional Statement
• The if statement evaluates an expression and if that evaluation is true
then the specified action is taken
if ( x < 10 ) x = 10;
• If the value of x is less than 10, make x equal to 10
• It could have been written:
if ( x < 10 )
x = 10;
• Or, alternatively:
if ( x < 10 ) { x = 10; }
April 22, 2023
If… else
• The if … else statement evaluates an expression and performs one
action if that evaluation is true or a different action if it is false.
if (x != oldx) {
System.out.print(“x was changed”);
}
else {
System.out.print(“x is unchanged”);
}
April 22, 2023
Nested if … else
if ( myVal > 100 ) {
if ( remainderOn == true) {
myVal = mVal % 100;
}
else {
myVal = myVal / 100.0;
}
}
else
{
System.out.print(“myVal is in range”);
}
April 22, 2023
else if
• Useful for choosing between alternatives:
if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed, execute code block #3
}
April 22, 2023
The Switch Statement
switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
default:
// if all previous tests fail then //execute code block #4
break;
}
April 22, 2023
The for loop
• Loop n times
for ( i = 0; i < n; n++ ) {
// this code body will execute n times
// i from 0 to n-1
}• Nested for:
for ( j = 0; j < 10; j++ ) {
for ( i = 0; i < 20; i++ ){
// this code body will execute 200 times
}
}
April 22, 2023
while loop
int response=10;
while (response < 1) {
System.out.println(response);
response++;
}
April 22, 2023
do {… } while loops
int response=10;
do {
System.out.println(response);
response++;
}while (response < 1);
April 22, 2023
Break
• A break statement causes an exit from the innermost containing
while, do, for or switch statement.
for ( int i = 0; i < maxID, i++ ) {
if ( userID[i] == targetID ) {
index = i;
break;
}
} // program jumps here after break
April 22, 2023
Continue
• Can only be used with while, do or for.
• The continue statement causes the innermost loop to start the next
iteration immediately
for ( int i = 0; i < maxID; i++ ) {
if ( userID[i] != -1 ) continue;
System.out.print( “UserID ” + i + “ :” + userID);
}
April 22, 2023
Constructors• A special method that is invoked while object is being created.• It MUST have same name as class name and does not have return type• It can be parameterized• When no constructor is defined java compiler provides a default
constructor
• invokes a constructor method with which you can set the initial data of
an object
• You may choose several different type of constructor with different
argument lists
April 22, 2023
public class book1
{
String title;
String author;
double price ;
int percentDiscount;
public book1(String tit, String auth,double prc,int perDisc)
{
title = tit;
author = auth;
price = prc;
percentDiscount = perDisc;
}
double getDiscountedPrice()
{
return price - (price*percentDiscount/100);
}
public static void main(String args[])
{
book1 b1 = new book1("Java 2","Herbert",435,14);
book1 b2 = new book1("Ajax Project in Java Technology",
"Smith",300,30);
System.out.println(b1.getDiscountedPrice());
System.out.println(b2.getDiscountedPrice());
}
}
April 22, 2023
Packages• In java application there can not be two classes with same
name.
• When application involves 100s of classes and 10s of third party library being used, it is very difficult to come out with unique meaningful name
• This can be achieved in java using ‘package’s.
• A package is name space within which each class has unique name
• A package can also be used as access control – it is possible to define a class or member of a class which is visible only within a specified package.
April 22, 2023
Packages Syntaxpackage xpublic class a {}
package x.ypublic class a {}
Class a belongs to package x
Class a belongs to package x.y. This is fine as both class belong to different package
package com.bredge.samplepublic class b {}
Class b belongs to package com.bredge.sample
April 22, 2023
Access Specifiers• There are three access Specifiers namely ‘public’, ‘private’ and
protected and four access levels(including default).
• Members of a class can be public, private or protected.
• That basically means member variables and methods can either be public, private or protected.
• Public members are accessible within and outside class.
• Private members are accessible only within class.
• The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
• When neither public nor private or protected mentioned, default access will be considered.
• Class can be public or default only.
April 22, 2023
Access Specifiers
• Default access specifier, i.e. when there is no public, private or protected is mentioned, has package level visibility.
• Default class members are visible to all other classes which belong to same package
private protected public defaultSame class Y Y Y YSame package sub-class N Y Y YSame package non-subclass N Y Y YDifferent Package subclass N Y Y NDifferent Package non-subclass N N Y N
Thank You