SlideShare a Scribd company logo
Origin of Java 
• World War-2 need of a platform independent 
language 
• Green by Sun Micro Systems comes up 
• Fails due to marketing issues et al 
• Analog-to-Digital Transit, Computer H/W 
advancement, Concept of World Wide Web and 
Internet, Need of security 
• Green transformed to Oak 
• 1994 Java makes official release 
sohamsengupta@yahoo.com1
Three Editions of Java 
• J2SE (Java 2 Standard Edititon) 
• J2EE (Java 2 Enterprise Edition) 
• J2ME (Java 2 Micro Edition) 
sohamsengupta@yahoo.com2
Java Data Types 
Numeric: 1. Whole Numbers 
sohamsengupta@yahoo.com3 
2. Fractions 
Whole Numbers: byte 1 byte default value 0 
short2 bytes default value 0 
int  4 bytes default value 0 
long 8 bytes default value 0 
Fractions: float 4 bytes default value 0.0f 
double 8 bytes default value 0 .0 
Symbolic: char  2 bytes (Sun Unicode Character) default 
value‘u0000’ 
Logical : boolean 1 byte default value false 
User Defined: class and interface (to be described later on)
Your First Java Program 
• In C consider the code snippet… 
#include<stdio.h> 
void main(){ 
printf(“Hello From Soham”); 
sohamsengupta@yahoo.com4 
}• 
The corresponding Java Code would be… 
class A 
{ 
public static void main(String[] args){ 
System.out.print(“Hello from Soham”); 
}}
Before I say more on Java some Do’s 
Soham was writing a program as on LHS. After typing out 1000 lines he 
felt he needed an extra statement in if branch, but poor Soham! What he 
did was 
sohamsengupta@yahoo.com5 
• if(condition) 
statement-1; 
statement-2; 
. 
. 
. 
Statement-1000; 
• if(condition) 
statement-1; 
ssttaatteemmeenntt--11AA;; 
statement-2; 
. 
. 
. 
Statement-1000
Poor Me! I intended something else 
I was supposed to type… 
• if(condition){ 
sohamsengupta@yahoo.com6 
statement-1; 
ssttaatteemmeenntt--11AA;; 
}} 
statement-2; 
. 
. 
. 
statement-1000 
• Moral: 
1. When you come across some 
if-else branch, or for, while, 
switch, or any method or 
block, at once type out the 
braces and then carry on with 
your code 
2. It’ll not only save you from 
my condition, but also it’ll 
save you quite a lot of time of 
compilation errors saying… 
“ } required”
More on Java 
Answers to some FAQ about Java 2 
• A java file is saved in .java extension 
• A java file, if successfully compiled, produces x+y number of .class 
files where x and y are the number of classes and interfaces in that 
file 
• In java, you can’t put anything except comments outside a class or 
sohamsengupta@yahoo.com7 
interface block 
• To run java program you need Java Virtual Machine(JVM) which 
comes as a part of JDK. 
• Successful compilation generates .class files which contain byte 
codes that is interpreted by JVM. So, java development generally 
uses both compiler and interpreter. 
• Java Byte codes are platform independent but JVM is different for 
different Operating Systems.
Features of Java 2 (J2SE 1.4) 
1. Platform independent…means runs on any HW+OS environment 
2. Java was developed using C++ but excludes the features like 
sohamsengupta@yahoo.com8 
pointers. 
3. Java is a purely typed language as it does not allow automatic type 
demotion (More on this later on) 
4. Java is object oriented, secure due to its various security features, 
reusable and portable,form-free and case sensitive and supports 
general logical statements like C/C++ 
5. Java is not only platform friendly but also is very much developer 
friendly. As support of this statement, Java does not have concept of 
garbage value. It will never let the program perform read operation 
on a non initialized local variable .Also, it saves you from getting 
tampered data due to overflow and/or underflow since it doesn’t 
allow automatic type demotion
Java Source File Name & Class Name 
1. A java source file may contain any number of classes and interfaces 
and there is no such hard-and-first rule that file name and class/ 
interface name should have relation…. But wait friends, this is 
applicable as long as the file contains no public class/interface. 
More concisely, a java source file must have the same name as that 
of the public class/interface in it. It’s thus implied that a java source 
file can contain one and only one public class/interface 
2. To compile a Java file, say, A.java you have to give the command 
sohamsengupta@yahoo.com9 
…>javac A.java 
3. If successful compilation occurs, you will surely want to run it. And 
your command is going to be …> java MyClass where MyClass is 
the class inside A.java that has then main method. 
4. Remember, MyClass need not always have the main method.
My Second Java Program 
#include<stdio.h> 
void main() 
{ 
int x=940; 
printf(“U scored good marksn”); 
printf(“Your marks is %d”,x); 
sohamsengupta@yahoo.com10 
} 
class A 
{ 
public static void main(String[] ar) 
{ 
int x=940; 
System.out.println(“U scored good 
marks”); 
System.out.print(“Your marks is ”+x); 
} 
}
Printing an output on the console 
• We generally use the syntax System.out.print() or System.out.println() 
to output text on the console. Difference between them is that println() 
can be used with no arguments where as print() can’t be used without 
an argument. Also, println() automatically appends a trailing new line 
character (‘n’) 
• Don’t ask me more about System.out because my plan is to climb up 
the Java tree step by step and I don’t want to stumble down the stairs. 
Yet, FYI, System is class under java.lang package and out is an static 
object belonging to System class and of type java.io.PrintStream. 
• Note the syntax: System.out.print(“Your marks is ”+x); 
• Here + is concatenation operator instead and apart 
from being the traditional addition operator. 
sohamsengupta@yahoo.com11
Dual Nature of + operator 
Look at the code snippet below and see the outputs 
int x=9; int y=6; 
15 
System.out.println(x+y); 
int x=9; int y=6; 
System.out.println(“Sum is ”+x+y); 
Sum is 96 
int x=9; int y=6; 
System.out.println(“Sum is ”+(x+y)); 
Sum is 15 
int x=9; int y=6; 
System.out.println(“Product is ”+x*y); 
Product is 54 
int x=9; int y=6; 
System.out.println(x+y+ “ is the sum”); 
15 is the sum 
int x=9; int y=6; 
System.out.println(x-y+ “ is difference”); 
3 is difference 
int x=9; int y=6; 
System.out.println(“Difference is”+x-y); 
Compilation error: 
Operator – cannot be applied to 
java.lang.String,int 
sohamsengupta@yahoo.com12
From the Experts’ Desk 
1. Since you can’t always afford to remember all the precedence rules and 
this sort of things, the Java Guru recommends that you should always 
use parentheses while using arithmetic expressions in the simplest way 
2. As you are mostly accustomed to C/C++, first you’ll ask for a 
counterpart of scanf() and cin>>. Yes. You can take input from console 
through keyboard. But as I’ve told you, wait till I make you climb to 
that level! Java, unlike C/C++ is not meant to be used as a mere 
programming language with console as you did with Turbo C++, 
generating Pascal triangles or Fibonacci Series et al. 
3. Today java is more of a technology than of a language itself. Java can 
carry out robust networking, enterprise web development to small 
mobile device programming. 
4. Note that Java handles all inputs as String, unlike C then tries to 
convert to the intended type. 
sohamsengupta@yahoo.com13
Java As a Typed language: code snippet 
sohamsengupta@yahoo.com14 
byte x=9; 
System.out.println(x); 
Here output will be 9 It’s OK to assign a value to 
a type within range 
byte x=129; 
System.out.println(x); 
Error: Possible loss of 
precision: found int , 
required byte 
Value beyond range. Range 
of byte –128 to +127 
byte x=(byte)129; 
System.out.println(x); 
Output: -127 (data 
tampered due to overflow) 
Explicit type casting may 
cost you to worry later 
int y=5; byte x=y; 
System.out.println(x); 
Error: Possible loss of 
precision: found int , 
required byte 
Though value is in range, 
type int can’t be 
automatically demoted. 
int y=5; byte x=(byte)y; 
System.out.println(x); 
OK. Output: 5 Explicit type demotion ok 
here but can cause OF/UF 
long y=8; int x=y; 
System.out.println(x); 
Guess yourself Automatica type demotion 
not allowed so error. 
float x=9.8; // Error 
Should be float x=9.8f; 
Error: possible loss of 
precision: found double 
required float 
9.8 is double and 9.8f/9.8F 
is float. This is because java 
is memory efficient
Java A Typed Language: Contd. 
1. boolean is the only data type that can’t be converted to 
any type nor any other type be converted to boolean. 
2. Implicit type demotion is not allowed in java. You have 
to do it explicitly. But before that make sure that it 
causes no overflow and/or underflow or both. 
3. Although char is 2 bytes and so is short, yet they are not 
compatible. char is automatically converted to int or 
higher. For hierarchy consult any standard book. 
4. char is unsigned strictly in java and note the following. 
char ch=-90; // Error 
char ch=90; System.out.println(ch); // output : Z 
char ch=90; System.out.println((int)ch);// output 90 
sohamsengupta@yahoo.com15
Operators: Unary & Binary 
1. Rule for Unary Operator: 
“If the operand is of a type which is below int in the hierarchy, the 
output is converted to int, else the type of the output is the type of 
the operand.” 
2. Rule for Binary Operator: 
“ If the Binary operator takes 2 operators one of type T1 and the 
other of type T2, and max(T1,T2) is less than or equal to int, the 
output is converted to int itself, else the output is of type 
max(T1,T2)” 
This rule is not applicable to increment and decrement operators 
Hold your breath dears! Lots of surprises await you in the next 
slide. 
sohamsengupta@yahoo.com16
Look at the code snippets below 
sohamsengupta@yahoo.com17 
byte x=9; x=-x; 
System.out.println(x); 
Error: Possible loss of 
precision found: int 
required: byte 
Rule-1: inputbyte 
Output int 
byte x=9; byte y=x+1; 
System.out.println(x); 
Same Error Rule:2 i/p byte, int 
O/p int 
byte x=7; byte y=2; 
short z=x+y; 
Same Error! Apply Rule-2 
long x=89; byte y=8; 
int z=x+y; 
Error! Apply Rule-2. Output is 
of type long 
byte x=9; x=x+8; Error Apply Rule-2: Output is 
of type int 
byte x=9; x+=8; x++; OK Rule-2 Not applicable 
for += and ++ operator 
char ch=‘%’; int x=100 
System.out.println(x+ch 
+ “ pure am I”); 
Output 137 pure am I Be careful. To avoid 
this, use parentheses or 
String ch=“%”;
Note the Following 
• byte x=‘c’; // is OK 
• int x=12; 
byte y=x; // Error 
• final int x=12; byte y=x; // IS OK 
• final int x=134; byte y=x; // Error out of range 
• This holds only when source data is less than or 
equal to int. 
• Adding the keyword “final” before a variable 
makes it constant. It can’t be changed and any 
code to change this will result in compilation error 
sohamsengupta@yahoo.com18
Note the following code snippets 
public static void main(String[] args){ 
int x; 
x++; 
System.out.println(x); 
} 
Error: variable 
x might not 
have been 
initialized. 
In Java there is no concept 
of garbage value. Without 
initializing a local variable 
u can’t perform read 
operation on it. 
sohamsengupta@yahoo.com19 
int x; 
if(6>4){x=8; } 
System.out.println(x); 
OK. Output will 
be 8 
6>4 is evaluated at compile 
time. So, since it’s true 
always, x must be 
initialized. 
int x; 
if(6<4){ x=8;} 
System.out.println(x); 
Error:variable 
x might not 
have been 
initialized. 
6<4 is evaluated at compile 
time. So, since it’s false 
always, x must not be 
initialized. 
Replace numerics by variables say, a & 
b. Observe the result, it’s error 
if(a>b){ x=8;} System.out.print(x); 
But making them final will be ok if a>b 
is true 
Error:variable 
x might not 
have been 
initialized. 
a>b or a<b is not evaluated 
during compilation time. 
So, it’s not sure if x is 
initialized or not. Hence 
Error

More Related Content

PPSX
Xmpp and java
PPTX
Protocol buffers
PPTX
Python
PPTX
Chapter 2.4
PPTX
Protocol Buffer.ppt
PPT
Ch01 basic-java-programs
PPT
Unit 8 Java
PDF
Augmenting and structuring user queries to support efficient free-form code s...
Xmpp and java
Protocol buffers
Python
Chapter 2.4
Protocol Buffer.ppt
Ch01 basic-java-programs
Unit 8 Java
Augmenting and structuring user queries to support efficient free-form code s...

What's hot (20)

PDF
Java programming basics
PPTX
Multithreading in java
PDF
FaCoY – A Code-to-Code Search Engine
PDF
Java Threads
PPTX
Reverse-engineering: Using GDB on Linux
PPT
Taking User Input in Java
PPT
Threads c sharp
PDF
Class notes(week 5) on command line arguments
PPTX
Java Notes
KEY
What's New In Python 2.4
PPTX
Threading in C#
PPTX
advanced java ppt
PPT
Threads And Synchronization in C#
PPTX
Std 12 Computer Chapter 7 Java Basics (Part 1)
PDF
Socket Programming In Python
PDF
Php interview questions with answer
PPT
Python session.11 By Shanmugam
PDF
Java Concurrency by Example
PPTX
Introduction to Python Programming
PPTX
Multithreading in java
Java programming basics
Multithreading in java
FaCoY – A Code-to-Code Search Engine
Java Threads
Reverse-engineering: Using GDB on Linux
Taking User Input in Java
Threads c sharp
Class notes(week 5) on command line arguments
Java Notes
What's New In Python 2.4
Threading in C#
advanced java ppt
Threads And Synchronization in C#
Std 12 Computer Chapter 7 Java Basics (Part 1)
Socket Programming In Python
Php interview questions with answer
Python session.11 By Shanmugam
Java Concurrency by Example
Introduction to Python Programming
Multithreading in java
Ad

Similar to Core java day1 (20)

PPT
00_Introduction to Java.ppt
PPTX
PPT
Introduction to Java Programming Part 2
PPT
Java Tutorial
PPT
Java tut1
PPT
Tutorial java
PPT
Java Tut1
PPTX
Java Notes by C. Sreedhar, GPREC
PPTX
Unit 1 of java part 2 basic introduction
PPT
Java basic tutorial by sanjeevini india
PPT
Java basic tutorial by sanjeevini india
PDF
Beyond PITS, Functional Principles for Software Architecture
PPTX
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
PPTX
Knowledge of Javascript
PPT
PPT
Learning Java 1 – Introduction
PPTX
Java programing language unit 1 introduction
PPTX
Functional Programming In Jdk8
PPTX
OCA_1Z0-808_Module00_Introduction_Java.pptx
PPSX
Java Tutorial
00_Introduction to Java.ppt
Introduction to Java Programming Part 2
Java Tutorial
Java tut1
Tutorial java
Java Tut1
Java Notes by C. Sreedhar, GPREC
Unit 1 of java part 2 basic introduction
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Beyond PITS, Functional Principles for Software Architecture
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
Knowledge of Javascript
Learning Java 1 – Introduction
Java programing language unit 1 introduction
Functional Programming In Jdk8
OCA_1Z0-808_Module00_Introduction_Java.pptx
Java Tutorial
Ad

More from Soham Sengupta (20)

PPTX
Spring method-level-secuirty
PPTX
Spring security mvc-1
PDF
JavaScript event handling assignment
PDF
Networking assignment 2
PDF
Networking assignment 1
PPT
Sohams cryptography basics
PPT
Network programming1
PPT
JSR-82 Bluetooth tutorial
PPT
Core java day2
PPT
Core java day4
PPT
Core java day5
PPT
Exceptions
PPSX
Java.lang.object
PPTX
Soham web security
PPTX
Html tables and_javascript
PPT
Html javascript
PPT
Java script
PPS
Sohamsg ajax
PPT
Spring method-level-secuirty
Spring security mvc-1
JavaScript event handling assignment
Networking assignment 2
Networking assignment 1
Sohams cryptography basics
Network programming1
JSR-82 Bluetooth tutorial
Core java day2
Core java day4
Core java day5
Exceptions
Java.lang.object
Soham web security
Html tables and_javascript
Html javascript
Java script
Sohamsg ajax

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PPTX
ai tools demonstartion for schools and inter college
PDF
Become an Agentblazer Champion Challenge
PDF
Jenkins: An open-source automation server powering CI/CD Automation
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PDF
Digital Strategies for Manufacturing Companies
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
System and Network Administraation Chapter 3
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
PDF
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PDF
Comprehensive Salesforce Implementation Services.pdf
PDF
Build Multi-agent using Agent Development Kit
PPTX
AIRLINE PRICE API | FLIGHT API COST |
PPTX
Introduction to Artificial Intelligence
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
ai tools demonstartion for schools and inter college
Become an Agentblazer Champion Challenge
Jenkins: An open-source automation server powering CI/CD Automation
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
Digital Strategies for Manufacturing Companies
A REACT POMODORO TIMER WEB APPLICATION.pdf
Which alternative to Crystal Reports is best for small or large businesses.pdf
System and Network Administraation Chapter 3
Materi_Pemrograman_Komputer-Looping.pptx
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
How to Migrate SBCGlobal Email to Yahoo Easily
ManageIQ - Sprint 268 Review - Slide Deck
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Comprehensive Salesforce Implementation Services.pdf
Build Multi-agent using Agent Development Kit
AIRLINE PRICE API | FLIGHT API COST |
Introduction to Artificial Intelligence

Core java day1

  • 1. Origin of Java • World War-2 need of a platform independent language • Green by Sun Micro Systems comes up • Fails due to marketing issues et al • Analog-to-Digital Transit, Computer H/W advancement, Concept of World Wide Web and Internet, Need of security • Green transformed to Oak • 1994 Java makes official release [email protected]
  • 2. Three Editions of Java • J2SE (Java 2 Standard Edititon) • J2EE (Java 2 Enterprise Edition) • J2ME (Java 2 Micro Edition) [email protected]
  • 3. Java Data Types Numeric: 1. Whole Numbers [email protected] 2. Fractions Whole Numbers: byte 1 byte default value 0 short2 bytes default value 0 int  4 bytes default value 0 long 8 bytes default value 0 Fractions: float 4 bytes default value 0.0f double 8 bytes default value 0 .0 Symbolic: char  2 bytes (Sun Unicode Character) default value‘u0000’ Logical : boolean 1 byte default value false User Defined: class and interface (to be described later on)
  • 4. Your First Java Program • In C consider the code snippet… #include<stdio.h> void main(){ printf(“Hello From Soham”); [email protected] }• The corresponding Java Code would be… class A { public static void main(String[] args){ System.out.print(“Hello from Soham”); }}
  • 5. Before I say more on Java some Do’s Soham was writing a program as on LHS. After typing out 1000 lines he felt he needed an extra statement in if branch, but poor Soham! What he did was [email protected] • if(condition) statement-1; statement-2; . . . Statement-1000; • if(condition) statement-1; ssttaatteemmeenntt--11AA;; statement-2; . . . Statement-1000
  • 6. Poor Me! I intended something else I was supposed to type… • if(condition){ [email protected] statement-1; ssttaatteemmeenntt--11AA;; }} statement-2; . . . statement-1000 • Moral: 1. When you come across some if-else branch, or for, while, switch, or any method or block, at once type out the braces and then carry on with your code 2. It’ll not only save you from my condition, but also it’ll save you quite a lot of time of compilation errors saying… “ } required”
  • 7. More on Java Answers to some FAQ about Java 2 • A java file is saved in .java extension • A java file, if successfully compiled, produces x+y number of .class files where x and y are the number of classes and interfaces in that file • In java, you can’t put anything except comments outside a class or [email protected] interface block • To run java program you need Java Virtual Machine(JVM) which comes as a part of JDK. • Successful compilation generates .class files which contain byte codes that is interpreted by JVM. So, java development generally uses both compiler and interpreter. • Java Byte codes are platform independent but JVM is different for different Operating Systems.
  • 8. Features of Java 2 (J2SE 1.4) 1. Platform independent…means runs on any HW+OS environment 2. Java was developed using C++ but excludes the features like [email protected] pointers. 3. Java is a purely typed language as it does not allow automatic type demotion (More on this later on) 4. Java is object oriented, secure due to its various security features, reusable and portable,form-free and case sensitive and supports general logical statements like C/C++ 5. Java is not only platform friendly but also is very much developer friendly. As support of this statement, Java does not have concept of garbage value. It will never let the program perform read operation on a non initialized local variable .Also, it saves you from getting tampered data due to overflow and/or underflow since it doesn’t allow automatic type demotion
  • 9. Java Source File Name & Class Name 1. A java source file may contain any number of classes and interfaces and there is no such hard-and-first rule that file name and class/ interface name should have relation…. But wait friends, this is applicable as long as the file contains no public class/interface. More concisely, a java source file must have the same name as that of the public class/interface in it. It’s thus implied that a java source file can contain one and only one public class/interface 2. To compile a Java file, say, A.java you have to give the command [email protected] …>javac A.java 3. If successful compilation occurs, you will surely want to run it. And your command is going to be …> java MyClass where MyClass is the class inside A.java that has then main method. 4. Remember, MyClass need not always have the main method.
  • 10. My Second Java Program #include<stdio.h> void main() { int x=940; printf(“U scored good marksn”); printf(“Your marks is %d”,x); [email protected] } class A { public static void main(String[] ar) { int x=940; System.out.println(“U scored good marks”); System.out.print(“Your marks is ”+x); } }
  • 11. Printing an output on the console • We generally use the syntax System.out.print() or System.out.println() to output text on the console. Difference between them is that println() can be used with no arguments where as print() can’t be used without an argument. Also, println() automatically appends a trailing new line character (‘n’) • Don’t ask me more about System.out because my plan is to climb up the Java tree step by step and I don’t want to stumble down the stairs. Yet, FYI, System is class under java.lang package and out is an static object belonging to System class and of type java.io.PrintStream. • Note the syntax: System.out.print(“Your marks is ”+x); • Here + is concatenation operator instead and apart from being the traditional addition operator. [email protected]
  • 12. Dual Nature of + operator Look at the code snippet below and see the outputs int x=9; int y=6; 15 System.out.println(x+y); int x=9; int y=6; System.out.println(“Sum is ”+x+y); Sum is 96 int x=9; int y=6; System.out.println(“Sum is ”+(x+y)); Sum is 15 int x=9; int y=6; System.out.println(“Product is ”+x*y); Product is 54 int x=9; int y=6; System.out.println(x+y+ “ is the sum”); 15 is the sum int x=9; int y=6; System.out.println(x-y+ “ is difference”); 3 is difference int x=9; int y=6; System.out.println(“Difference is”+x-y); Compilation error: Operator – cannot be applied to java.lang.String,int [email protected]
  • 13. From the Experts’ Desk 1. Since you can’t always afford to remember all the precedence rules and this sort of things, the Java Guru recommends that you should always use parentheses while using arithmetic expressions in the simplest way 2. As you are mostly accustomed to C/C++, first you’ll ask for a counterpart of scanf() and cin>>. Yes. You can take input from console through keyboard. But as I’ve told you, wait till I make you climb to that level! Java, unlike C/C++ is not meant to be used as a mere programming language with console as you did with Turbo C++, generating Pascal triangles or Fibonacci Series et al. 3. Today java is more of a technology than of a language itself. Java can carry out robust networking, enterprise web development to small mobile device programming. 4. Note that Java handles all inputs as String, unlike C then tries to convert to the intended type. [email protected]
  • 14. Java As a Typed language: code snippet [email protected] byte x=9; System.out.println(x); Here output will be 9 It’s OK to assign a value to a type within range byte x=129; System.out.println(x); Error: Possible loss of precision: found int , required byte Value beyond range. Range of byte –128 to +127 byte x=(byte)129; System.out.println(x); Output: -127 (data tampered due to overflow) Explicit type casting may cost you to worry later int y=5; byte x=y; System.out.println(x); Error: Possible loss of precision: found int , required byte Though value is in range, type int can’t be automatically demoted. int y=5; byte x=(byte)y; System.out.println(x); OK. Output: 5 Explicit type demotion ok here but can cause OF/UF long y=8; int x=y; System.out.println(x); Guess yourself Automatica type demotion not allowed so error. float x=9.8; // Error Should be float x=9.8f; Error: possible loss of precision: found double required float 9.8 is double and 9.8f/9.8F is float. This is because java is memory efficient
  • 15. Java A Typed Language: Contd. 1. boolean is the only data type that can’t be converted to any type nor any other type be converted to boolean. 2. Implicit type demotion is not allowed in java. You have to do it explicitly. But before that make sure that it causes no overflow and/or underflow or both. 3. Although char is 2 bytes and so is short, yet they are not compatible. char is automatically converted to int or higher. For hierarchy consult any standard book. 4. char is unsigned strictly in java and note the following. char ch=-90; // Error char ch=90; System.out.println(ch); // output : Z char ch=90; System.out.println((int)ch);// output 90 [email protected]
  • 16. Operators: Unary & Binary 1. Rule for Unary Operator: “If the operand is of a type which is below int in the hierarchy, the output is converted to int, else the type of the output is the type of the operand.” 2. Rule for Binary Operator: “ If the Binary operator takes 2 operators one of type T1 and the other of type T2, and max(T1,T2) is less than or equal to int, the output is converted to int itself, else the output is of type max(T1,T2)” This rule is not applicable to increment and decrement operators Hold your breath dears! Lots of surprises await you in the next slide. [email protected]
  • 17. Look at the code snippets below [email protected] byte x=9; x=-x; System.out.println(x); Error: Possible loss of precision found: int required: byte Rule-1: inputbyte Output int byte x=9; byte y=x+1; System.out.println(x); Same Error Rule:2 i/p byte, int O/p int byte x=7; byte y=2; short z=x+y; Same Error! Apply Rule-2 long x=89; byte y=8; int z=x+y; Error! Apply Rule-2. Output is of type long byte x=9; x=x+8; Error Apply Rule-2: Output is of type int byte x=9; x+=8; x++; OK Rule-2 Not applicable for += and ++ operator char ch=‘%’; int x=100 System.out.println(x+ch + “ pure am I”); Output 137 pure am I Be careful. To avoid this, use parentheses or String ch=“%”;
  • 18. Note the Following • byte x=‘c’; // is OK • int x=12; byte y=x; // Error • final int x=12; byte y=x; // IS OK • final int x=134; byte y=x; // Error out of range • This holds only when source data is less than or equal to int. • Adding the keyword “final” before a variable makes it constant. It can’t be changed and any code to change this will result in compilation error [email protected]
  • 19. Note the following code snippets public static void main(String[] args){ int x; x++; System.out.println(x); } Error: variable x might not have been initialized. In Java there is no concept of garbage value. Without initializing a local variable u can’t perform read operation on it. [email protected] int x; if(6>4){x=8; } System.out.println(x); OK. Output will be 8 6>4 is evaluated at compile time. So, since it’s true always, x must be initialized. int x; if(6<4){ x=8;} System.out.println(x); Error:variable x might not have been initialized. 6<4 is evaluated at compile time. So, since it’s false always, x must not be initialized. Replace numerics by variables say, a & b. Observe the result, it’s error if(a>b){ x=8;} System.out.print(x); But making them final will be ok if a>b is true Error:variable x might not have been initialized. a>b or a<b is not evaluated during compilation time. So, it’s not sure if x is initialized or not. Hence Error