SlideShare uma empresa Scribd logo
1 de 44
Topic 2: Java Basics
Readings: Chapter 3
Advanced Programming Techniques
Objective and Outline
• Objective
– Show basic programming concepts
• Outline
– What do java programs look like?
– Basic ingredients
• Java primitive types
• Variables and constants
• Operators and control flow
– Simple commonly used built-ins.
• Simple input/output
• Arrays and Strings
What do java program look like?
public class MyProgram {
public static void main(String
args[])
{
System.out.println(“Hello world!”);
}
} //File: MyProgram.javapublic: Access modifier
class: everything is inside a class
MyProgram: class name.
matches file name.
Case sensitive
main: method of the wrapping
class
Compilation and run:
javac MyProgram.java
=> MyProgram.class
java MyProgram
Objective and Outline
• Outline
– What do java programs look like?
– Basic ingredients
• Java primitive types
• Variables and constants
• Operators and control flow
– Simple commonly used built-ins.
• Simple input/output
• Arrays and Strings
Basic Ingredients/Primitive Types
• Integers
– byte (1 byte, -128 to 127)
– short (2 bytes)
– int (4 bytes)
– long (8 bytes)
• Floating-point types
– float (4 bytes, 6-7 significant decimal digits)
– double (8 bytes, 15 significant decimal digits)
• char (2 byte, Unicode) (ASCII 1 byte)
• boolean (true or false)
• Those are all the primitive types in Java. Everything else is an object.
For really large numbers use
BigInteger and BigDecimal
classes
Basic Ingredients/Primitive Types
• Legal conversions between numeric types
– Arrows indicate direction of legal and automatic conversion
• double x = 123;
• long x = 123456789; float y = x;
– Solid arrow: no loss of precision
– Dotted arrow: might lose precision
• z=1.234567E8
bytes short
double
int long
float
char
Basic Ingredients/Primitive Types
• Conversion in the opposite direction required explicit cast.
– double x = 9.997;
– int num = (int) x;
– int num = x; // does not compile
Can easily lead to the loss of precision (round-up errors)
• Cannot convert between boolean and numerical values.
bytes short
double
int long
float
char
Objective and Outline
• Outline
– What do java programs look like?
– Basic ingredients
• Java primitive types
• Variables and constants
• Operators and control flow
– Simple commonly used built-ins.
• Simple input/output
• Arrays and Strings
Basic Ingredients/Variables and Constants
• Variables can be declared anywhere
for (int i = 0; i < 20; i++) {
System.out.println(“Hi”);
char ch = ‘A’;
}
double pi = 3.14159;
• Java compilers require initialization of local variables before use
public void someMethod()
{ …
int x; // does not compile
}
• Instance variables of class automatically initialized.
Basic Ingredients/Variables and Constants
final marks a variable “read-only”
Variable is assigned once and cannot be changed
public void someMethod()
{ final double pi = 3.14159;
.. .. ..
pi = 3.14; // illegal
}
Use static final to define constants which are available to multiple
methods inside a single class
public class Time {
static final int MinHour = 0;
static final int MaxHour = 23;
private int hour, minute;
// these properties are set to 0
// unless overwritten by constructor
… }
Objective and Outline
• Outline
– What do java programs look like?
– Basic ingredients
• Java primitive types
• Variables and constants
• Operators and control flow
– Simple commonly used built-ins.
• Simple input/output
• Arrays and Strings
Basic Ingredients/Operators
• Basically the same as C++:
+, -, *, /, %, ++, --,
<, <=, >, >=, ==, !=,
!, &&, ||
=, +=, -=, *=, /=, %=,
• User cannot “overload” operators; although + is overloaded to do string
concatenation
– In C++:
• Int x=0; x += 1;
• String& String::operator+=( const String &s)..
• Note that methods can be overloaded
Basic Ingredients /Operators
No Pointers!
No explicit pointer types (although objects are implemented as
references)
No & or * operators
In C++:
int *i = (int *) malloc( 3 * sizeof(int));
(i+1)* = 2;
int& y = &i;
No pointer arithmetic
No function pointers
Basic Ingredients/Control flow
Basically the same as C++:
if (boolean-expr)
statement; (has optional else)
if ( x = 0 ) //leads to compiling error
for (expr; boolean-expr; expr)
statement;
while (boolean-expr)
statement; (do-while variant also)
switch (integer-expr)
case constant: statement; break;
Basic Ingredients/Control flow
Labeled break;
Int n;
read_data:
while (…)
{ … for (…)
{
String input = JOptionPane.showInputDialog
(“Enter a number >=0”);
N = Integer.parseInt(input);
if ( n < 0 )
break read_data;
}
}
// moves to here when n<0.
• No explicit goto (no union, no struct);
Colon
Basic Ingredients/Control flow
Recursion
Basically the same as C++:
public class Factorial
{
public static int factorial( int n ) {
if ( n <=1 ) return 1;
return factorial( n-1 ) * n;
}
public static void main(String args[])
{
System.out.println( factorial ( 4 ) );
}
}//Factorial.java
Objective and Outline
• Outline
– What do java programs look like?
– Basic ingredients
• Java primitive types
• Variables and constants
• Operators and control flow
– Simple commonly used built-ins.
• Simple input/output
• Arrays and Strings
Simple Input/Output
• Contents
– Writing to standard output
– Reading keyboard input via dialog box
– Formatting output
• We discuss I/O in more detail later.
Simple Input/Output
• It is easy to print output to the “standard output
device (the console window) by using the
predefined Stream objects out
System.out.print(“Your name is “ + name + “
and you are “ + num + “ years old.”);
Simple Input/Output
• It is a bit more complex to read input from the “standard input device” using
Stream.
• However it is easy to supply a dialog box for keyboard input:
JOptionPane.showInputDialog(promptString)
The return value is the string that the user typed
• Example: InputTest.java
Simple Input/Output
• Need to include this statement:
import javax.swing.*;
//JOptionPane class is defined in that package
• For example: you can query name of the user by:
String name= JOptionPane.showInputDialog(“Your
name:”);
• To read in a number, use the Integer.parseInt or
Double.parseDouble method to convert the string to its numeric
value. For example,
String input= JOptionPane.showInputDialog(“Your
age:”);
int age = Integer.parseInt(input);
• End the program with the method call: System.exit(0);
Simple Input/Output
• Use string formatters provided in java.text.NumberFormat to format
output:
NumberFormat.getNumberInstance() // for numbers
NumberFormat.getCurrencyInstance()// for currency values
NumberFormat.getPercentInstance()// for percentage values
• For Example:
double x = 10000.0 / 3.0;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(4);
nf.setMinimumIntegerDigits(6);
System.out.println(nf.format(x)); //003,333.3333
Objective and Outline
• Outline
– What do java programs look like?
– Basic ingredients
• Java primitive types
• Variables and constants
• Operators and control flow
– Simple commonly used built-ins.
• Simple input/output
• Arrays and Strings
Arrays
• Contents
– Arrays are objects
– Arrays are implemented as references
– Multidimensional arrays
Arrays
• Arrays are objects of class java.lang.reflect.Array
• Can’t specify size when declaring array
int arr[3]; // not legal in Java!
int arr[]; // okay
int[] arr; // okay (same as previous line)
• Arrays (as all objects) are dynamically allocated
int[] arr = new int[3];
• Before allocation, array variable is null
• All elements are zeroed when array allocated
• Destroyed automatically by garbage collector. No delete operator
• Shorthand to declare, allocate, and initialize
int[] arr = { 5, 10, 15, 20};
Arrays
• Java array (object) always knows its own length
int[] arr = {5, 20, 15, 10};
System.out.println(“Length is ” + arr.length);
• Elements indexed from 0 to length-1, like C++
• Raises exception for “ArrayIndexOutOfBounds”
• Length is fixed when allocated; create new array and
copy over to change length
Arrays
• Used in similar way as ordinary arrays
int sum(int[] arr)
{
int i, sum = 0;
for (i=0; i < arr.length; i++)
sum += arr[i];
return sum;
}
Arrays are references
• Arrays are objects, hence, are implemented as references
(reference is a pointer in disguise)
int[] arr = {5, 20, 15, 10};
int[] b = arr;
b[0] = 3; // arr[0] also becomes 3!
• Array copying (java.lang.System)
System.arraycopy(from, fromIndex, to, toindex, count);
int[] c;
System.arraycopy(arr, 0, c, 0, 4);
• Array sorting (java.util.Arrays)
Arrays.sort(arr) //use a tuned QuickSort
Array Examples
public class ArrayRef {
public static void main( String[] args ) {
int [] a = {0, 1, 2, 3, 4};
int [] b = {10, 11, 12, 13, 14};
a = b;
b = new int[] { 20, 21, 22, 23, 24 };
for (int i=0; i<a.length && i<b.length; i++)
{ System.out.println( a[i]+ ” ”+ b[i] ); }
}
}
// ArrayRef.java
//what is the output ?
Notice this quote
public class Swapping
{ public static void main(String argv[])
{ int[] a = {1,2,3};
for (int i=0; i<3; i++)
System.out.print(a[i]+" ");
System.out.print(“n”);
swap(a,0,2);
for (int i=0; i<3; i++)
System.out.print(a[i]+" ");
System.out.print(“n”);
}
public static void swap(int[] a, int i, int j)
{ int temp = a[j];
a[j]=a[i];
a[i]=temp;
}
} //Swapping.java
Multidimensional Arrays
int[][] matrix = new int[5][10];
int[] firstRow = matrix[0]; //ref to
1st row
int[] secondRow = matrix[1]; //ref to
2nd row
int firstElem = matrix[0][0];
firstElem = firstRow[0];
Strings
• Contents
– Strings are objects, immutable, differ from arrays
– Basic methods on Strings
– Convert String representation of numbers into
numbers
– StringBuffer, mutable version of Strings
String
• Java.lang.String
• Java.lang.StringBuffer
• String is an object
• Creating a String
– form string literal between double quotes
String s = “Hello, World!”;
– by using the new keyword
String s = new String(“Java”);
Accessor Methods
• String.length()
– obtain the length of the string
• String.charAt(int n)
– obtain the character at the nth position
Strings
• String is a class (java.lang.String)offering methods for almost
anything
String s = “a string literal”;
• + is concatenation, when you concatenate a string with a value that
is not a string, the latter is converted to a string
s = “The year is ” + 2002 + “!”;
• Everything can be converted to a string representation including
primitive types and objects (topic 3, class object)
Strings
• A String is not an array. It is immutable. You cannot change a String
– but you can change the contents of a String variable and make it refer to a
different String.
String s = “Hello”;
s[2]=‘a’; // Illegal
s = “Bye”; //Legal
• Equality test:
s.equals(t) // determines whether s and t are same
s == t// determines whether s and t stored at same location
String Example
public class StringExample
{ public static void main(String argv[])
{
String h = “hello”;
String w = “world”;
System.out.println(h + “ “ +w);
w = h.substring(1,3);
w += "binky";
for (int i = 0; i < w.length(); i++)
System.out.println(w.charAt(i));
int pos = w.indexOf("in");
System.out.println("Starting position of "in
" in string " " + w + " " is " + pos);
String Example
if ( h=="hello" )
System.out.println(
"String h == "hello" ");
if ( "hello".equals(h) )
System.out.println(""hello"
== string h ");
} }
} //StringExample.java
Example - String
• To print a string in reverse order
class ReverseString {
public static void reverseIt(String source) {
int i, len = source.length();
for (i = (len - 1); i >= 0; i--) {
System.out.print(source.charAt(i));
}
}
}
Convert String to number
• String class itself does not provide such a
conversion
• Type wrapper classes (Integer, Double,
Float and Long) provide a method valueOf
to do the job
String piStr = “3.14159”;
Float pi = Float.valueOf(piStr);
StringBuffer
• The String class is used for constant strings
• While StringBuffer is for strings that can
change
• StringBuffer contains a method
tostring() which returns the string value
being held
• Since String is immutable, it is “cheaper”!
StringBuffer
class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--) {
dest.append(source.charAt(i));
}
return dest.toString();
}
}
StringBuffer
• StringBuffer(int length)
– leaving the length undetermined is less efficient
• length, charAt, capacity
• append, insert, substring
• toString
StringBuffer
StringBuffer sb = new StringBuffer("Drink Java!");
StringBuffer prev_sb = sb;
sb.insert(6, "Hot ");
sb.append(" Cheer!");
System.out.println(sb.toString() + " : " +
sb.capacity());
System.out.println("prev_sb becomes " + prev_sb );
**** output *****
Drink Hot Java! Cheer! : 27 (initial size + 16)
prev_sb becomes Drink Hot Java! Cheer!

Mais conteúdo relacionado

Mais procurados

Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsRasan Samarasinghe
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Vadim Dubs
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#Rasan Samarasinghe
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NETRasan Samarasinghe
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 

Mais procurados (20)

Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 
Java8
Java8Java8
Java8
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 

Destaque

Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate TrainingArjun Sridhar U R
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training Arjun Sridhar U R
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project WorkshopArjun Sridhar U R
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list Mumbai Academisc
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in JavaPokequesthero
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingArjun Sridhar U R
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationRasan Samarasinghe
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list Mumbai Academisc
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesRasan Samarasinghe
 
Yaazli International Java Training
Yaazli International Java Training Yaazli International Java Training
Yaazli International Java Training Arjun Sridhar U R
 
Java notes 1 - operators control-flow
Java notes   1 - operators control-flowJava notes   1 - operators control-flow
Java notes 1 - operators control-flowMohammed Sikander
 

Destaque (20)

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Savr
SavrSavr
Savr
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
 
09events
09events09events
09events
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Java Basic Operators
Java Basic OperatorsJava Basic Operators
Java Basic Operators
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
 
Yaazli International Java Training
Yaazli International Java Training Yaazli International Java Training
Yaazli International Java Training
 
Java notes 1 - operators control-flow
Java notes   1 - operators control-flowJava notes   1 - operators control-flow
Java notes 1 - operators control-flow
 

Semelhante a Java Basics: Primitive Types, Variables, Arrays and Strings

Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operatorsraksharao
 
Reading and writting v2
Reading and writting v2Reading and writting v2
Reading and writting v2ASU Online
 
Reading and writting
Reading and writtingReading and writting
Reading and writtingandreeamolnar
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
Java PSkills-session2.pptx
Java PSkills-session2.pptxJava PSkills-session2.pptx
Java PSkills-session2.pptxssuser99ca78
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 

Semelhante a Java Basics: Primitive Types, Variables, Arrays and Strings (20)

Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
C
CC
C
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Reading and writting v2
Reading and writting v2Reading and writting v2
Reading and writting v2
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Basic_Java_02.pptx
Basic_Java_02.pptxBasic_Java_02.pptx
Basic_Java_02.pptx
 
Reading and writting
Reading and writtingReading and writting
Reading and writting
 
Java introduction
Java introductionJava introduction
Java introduction
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java PSkills-session2.pptx
Java PSkills-session2.pptxJava PSkills-session2.pptx
Java PSkills-session2.pptx
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 

Mais de Waheed Warraich (11)

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
java networking
 java networking java networking
java networking
 
java threads
java threadsjava threads
java threads
 
java applets
java appletsjava applets
java applets
 
java swing
java swingjava swing
java swing
 
08graphics
08graphics08graphics
08graphics
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
 
05io
05io05io
05io
 
04inherit
04inherit04inherit
04inherit
 
03class
03class03class
03class
 
01intro
01intro01intro
01intro
 

Último

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 

Último (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 

Java Basics: Primitive Types, Variables, Arrays and Strings

  • 1. Topic 2: Java Basics Readings: Chapter 3 Advanced Programming Techniques
  • 2. Objective and Outline • Objective – Show basic programming concepts • Outline – What do java programs look like? – Basic ingredients • Java primitive types • Variables and constants • Operators and control flow – Simple commonly used built-ins. • Simple input/output • Arrays and Strings
  • 3. What do java program look like? public class MyProgram { public static void main(String args[]) { System.out.println(“Hello world!”); } } //File: MyProgram.javapublic: Access modifier class: everything is inside a class MyProgram: class name. matches file name. Case sensitive main: method of the wrapping class Compilation and run: javac MyProgram.java => MyProgram.class java MyProgram
  • 4. Objective and Outline • Outline – What do java programs look like? – Basic ingredients • Java primitive types • Variables and constants • Operators and control flow – Simple commonly used built-ins. • Simple input/output • Arrays and Strings
  • 5. Basic Ingredients/Primitive Types • Integers – byte (1 byte, -128 to 127) – short (2 bytes) – int (4 bytes) – long (8 bytes) • Floating-point types – float (4 bytes, 6-7 significant decimal digits) – double (8 bytes, 15 significant decimal digits) • char (2 byte, Unicode) (ASCII 1 byte) • boolean (true or false) • Those are all the primitive types in Java. Everything else is an object. For really large numbers use BigInteger and BigDecimal classes
  • 6. Basic Ingredients/Primitive Types • Legal conversions between numeric types – Arrows indicate direction of legal and automatic conversion • double x = 123; • long x = 123456789; float y = x; – Solid arrow: no loss of precision – Dotted arrow: might lose precision • z=1.234567E8 bytes short double int long float char
  • 7. Basic Ingredients/Primitive Types • Conversion in the opposite direction required explicit cast. – double x = 9.997; – int num = (int) x; – int num = x; // does not compile Can easily lead to the loss of precision (round-up errors) • Cannot convert between boolean and numerical values. bytes short double int long float char
  • 8. Objective and Outline • Outline – What do java programs look like? – Basic ingredients • Java primitive types • Variables and constants • Operators and control flow – Simple commonly used built-ins. • Simple input/output • Arrays and Strings
  • 9. Basic Ingredients/Variables and Constants • Variables can be declared anywhere for (int i = 0; i < 20; i++) { System.out.println(“Hi”); char ch = ‘A’; } double pi = 3.14159; • Java compilers require initialization of local variables before use public void someMethod() { … int x; // does not compile } • Instance variables of class automatically initialized.
  • 10. Basic Ingredients/Variables and Constants final marks a variable “read-only” Variable is assigned once and cannot be changed public void someMethod() { final double pi = 3.14159; .. .. .. pi = 3.14; // illegal } Use static final to define constants which are available to multiple methods inside a single class public class Time { static final int MinHour = 0; static final int MaxHour = 23; private int hour, minute; // these properties are set to 0 // unless overwritten by constructor … }
  • 11. Objective and Outline • Outline – What do java programs look like? – Basic ingredients • Java primitive types • Variables and constants • Operators and control flow – Simple commonly used built-ins. • Simple input/output • Arrays and Strings
  • 12. Basic Ingredients/Operators • Basically the same as C++: +, -, *, /, %, ++, --, <, <=, >, >=, ==, !=, !, &&, || =, +=, -=, *=, /=, %=, • User cannot “overload” operators; although + is overloaded to do string concatenation – In C++: • Int x=0; x += 1; • String& String::operator+=( const String &s).. • Note that methods can be overloaded
  • 13. Basic Ingredients /Operators No Pointers! No explicit pointer types (although objects are implemented as references) No & or * operators In C++: int *i = (int *) malloc( 3 * sizeof(int)); (i+1)* = 2; int& y = &i; No pointer arithmetic No function pointers
  • 14. Basic Ingredients/Control flow Basically the same as C++: if (boolean-expr) statement; (has optional else) if ( x = 0 ) //leads to compiling error for (expr; boolean-expr; expr) statement; while (boolean-expr) statement; (do-while variant also) switch (integer-expr) case constant: statement; break;
  • 15. Basic Ingredients/Control flow Labeled break; Int n; read_data: while (…) { … for (…) { String input = JOptionPane.showInputDialog (“Enter a number >=0”); N = Integer.parseInt(input); if ( n < 0 ) break read_data; } } // moves to here when n<0. • No explicit goto (no union, no struct); Colon
  • 16. Basic Ingredients/Control flow Recursion Basically the same as C++: public class Factorial { public static int factorial( int n ) { if ( n <=1 ) return 1; return factorial( n-1 ) * n; } public static void main(String args[]) { System.out.println( factorial ( 4 ) ); } }//Factorial.java
  • 17. Objective and Outline • Outline – What do java programs look like? – Basic ingredients • Java primitive types • Variables and constants • Operators and control flow – Simple commonly used built-ins. • Simple input/output • Arrays and Strings
  • 18. Simple Input/Output • Contents – Writing to standard output – Reading keyboard input via dialog box – Formatting output • We discuss I/O in more detail later.
  • 19. Simple Input/Output • It is easy to print output to the “standard output device (the console window) by using the predefined Stream objects out System.out.print(“Your name is “ + name + “ and you are “ + num + “ years old.”);
  • 20. Simple Input/Output • It is a bit more complex to read input from the “standard input device” using Stream. • However it is easy to supply a dialog box for keyboard input: JOptionPane.showInputDialog(promptString) The return value is the string that the user typed • Example: InputTest.java
  • 21. Simple Input/Output • Need to include this statement: import javax.swing.*; //JOptionPane class is defined in that package • For example: you can query name of the user by: String name= JOptionPane.showInputDialog(“Your name:”); • To read in a number, use the Integer.parseInt or Double.parseDouble method to convert the string to its numeric value. For example, String input= JOptionPane.showInputDialog(“Your age:”); int age = Integer.parseInt(input); • End the program with the method call: System.exit(0);
  • 22. Simple Input/Output • Use string formatters provided in java.text.NumberFormat to format output: NumberFormat.getNumberInstance() // for numbers NumberFormat.getCurrencyInstance()// for currency values NumberFormat.getPercentInstance()// for percentage values • For Example: double x = 10000.0 / 3.0; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(4); nf.setMinimumIntegerDigits(6); System.out.println(nf.format(x)); //003,333.3333
  • 23. Objective and Outline • Outline – What do java programs look like? – Basic ingredients • Java primitive types • Variables and constants • Operators and control flow – Simple commonly used built-ins. • Simple input/output • Arrays and Strings
  • 24. Arrays • Contents – Arrays are objects – Arrays are implemented as references – Multidimensional arrays
  • 25. Arrays • Arrays are objects of class java.lang.reflect.Array • Can’t specify size when declaring array int arr[3]; // not legal in Java! int arr[]; // okay int[] arr; // okay (same as previous line) • Arrays (as all objects) are dynamically allocated int[] arr = new int[3]; • Before allocation, array variable is null • All elements are zeroed when array allocated • Destroyed automatically by garbage collector. No delete operator • Shorthand to declare, allocate, and initialize int[] arr = { 5, 10, 15, 20};
  • 26. Arrays • Java array (object) always knows its own length int[] arr = {5, 20, 15, 10}; System.out.println(“Length is ” + arr.length); • Elements indexed from 0 to length-1, like C++ • Raises exception for “ArrayIndexOutOfBounds” • Length is fixed when allocated; create new array and copy over to change length
  • 27. Arrays • Used in similar way as ordinary arrays int sum(int[] arr) { int i, sum = 0; for (i=0; i < arr.length; i++) sum += arr[i]; return sum; }
  • 28. Arrays are references • Arrays are objects, hence, are implemented as references (reference is a pointer in disguise) int[] arr = {5, 20, 15, 10}; int[] b = arr; b[0] = 3; // arr[0] also becomes 3! • Array copying (java.lang.System) System.arraycopy(from, fromIndex, to, toindex, count); int[] c; System.arraycopy(arr, 0, c, 0, 4); • Array sorting (java.util.Arrays) Arrays.sort(arr) //use a tuned QuickSort
  • 29. Array Examples public class ArrayRef { public static void main( String[] args ) { int [] a = {0, 1, 2, 3, 4}; int [] b = {10, 11, 12, 13, 14}; a = b; b = new int[] { 20, 21, 22, 23, 24 }; for (int i=0; i<a.length && i<b.length; i++) { System.out.println( a[i]+ ” ”+ b[i] ); } } } // ArrayRef.java //what is the output ? Notice this quote
  • 30. public class Swapping { public static void main(String argv[]) { int[] a = {1,2,3}; for (int i=0; i<3; i++) System.out.print(a[i]+" "); System.out.print(“n”); swap(a,0,2); for (int i=0; i<3; i++) System.out.print(a[i]+" "); System.out.print(“n”); } public static void swap(int[] a, int i, int j) { int temp = a[j]; a[j]=a[i]; a[i]=temp; } } //Swapping.java
  • 31. Multidimensional Arrays int[][] matrix = new int[5][10]; int[] firstRow = matrix[0]; //ref to 1st row int[] secondRow = matrix[1]; //ref to 2nd row int firstElem = matrix[0][0]; firstElem = firstRow[0];
  • 32. Strings • Contents – Strings are objects, immutable, differ from arrays – Basic methods on Strings – Convert String representation of numbers into numbers – StringBuffer, mutable version of Strings
  • 33. String • Java.lang.String • Java.lang.StringBuffer • String is an object • Creating a String – form string literal between double quotes String s = “Hello, World!”; – by using the new keyword String s = new String(“Java”);
  • 34. Accessor Methods • String.length() – obtain the length of the string • String.charAt(int n) – obtain the character at the nth position
  • 35. Strings • String is a class (java.lang.String)offering methods for almost anything String s = “a string literal”; • + is concatenation, when you concatenate a string with a value that is not a string, the latter is converted to a string s = “The year is ” + 2002 + “!”; • Everything can be converted to a string representation including primitive types and objects (topic 3, class object)
  • 36. Strings • A String is not an array. It is immutable. You cannot change a String – but you can change the contents of a String variable and make it refer to a different String. String s = “Hello”; s[2]=‘a’; // Illegal s = “Bye”; //Legal • Equality test: s.equals(t) // determines whether s and t are same s == t// determines whether s and t stored at same location
  • 37. String Example public class StringExample { public static void main(String argv[]) { String h = “hello”; String w = “world”; System.out.println(h + “ “ +w); w = h.substring(1,3); w += "binky"; for (int i = 0; i < w.length(); i++) System.out.println(w.charAt(i)); int pos = w.indexOf("in"); System.out.println("Starting position of "in " in string " " + w + " " is " + pos);
  • 38. String Example if ( h=="hello" ) System.out.println( "String h == "hello" "); if ( "hello".equals(h) ) System.out.println(""hello" == string h "); } } } //StringExample.java
  • 39. Example - String • To print a string in reverse order class ReverseString { public static void reverseIt(String source) { int i, len = source.length(); for (i = (len - 1); i >= 0; i--) { System.out.print(source.charAt(i)); } } }
  • 40. Convert String to number • String class itself does not provide such a conversion • Type wrapper classes (Integer, Double, Float and Long) provide a method valueOf to do the job String piStr = “3.14159”; Float pi = Float.valueOf(piStr);
  • 41. StringBuffer • The String class is used for constant strings • While StringBuffer is for strings that can change • StringBuffer contains a method tostring() which returns the string value being held • Since String is immutable, it is “cheaper”!
  • 42. StringBuffer class ReverseString { public static String reverseIt(String source) { int i, len = source.length(); StringBuffer dest = new StringBuffer(len); for (i = (len - 1); i >= 0; i--) { dest.append(source.charAt(i)); } return dest.toString(); } }
  • 43. StringBuffer • StringBuffer(int length) – leaving the length undetermined is less efficient • length, charAt, capacity • append, insert, substring • toString
  • 44. StringBuffer StringBuffer sb = new StringBuffer("Drink Java!"); StringBuffer prev_sb = sb; sb.insert(6, "Hot "); sb.append(" Cheer!"); System.out.println(sb.toString() + " : " + sb.capacity()); System.out.println("prev_sb becomes " + prev_sb ); **** output ***** Drink Hot Java! Cheer! : 27 (initial size + 16) prev_sb becomes Drink Hot Java! Cheer!