Java Programming Java Basics. Data Types Java has two main categories of data types: –Primitive data types Built in data types Many very similar to C++

Slides:



Advertisements
Similar presentations
STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
Advertisements

Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Constants and Data Types Constants Data Types Reading for this class: L&L,
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
Java Syntax Primitive data types Operators Control statements.
Pemrograman Dasar - Data Types1 THINGS & STUFF Identifier, Variable, Constant, Data type, operator, expression, assignment, javadoc.
String Escape Sequences
Programming Principles Data types and Variables. Data types Variables are nothing but reserved memory locations to store values. This means that when.
Agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays 2.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1 Course Lectures Available on line:
CSCI 1100/1202 January 16, Why do we need variables? To store intermediate results in a long computation. To store a value that is used more than.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 4.
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
CPS120: Introduction to Computer Science
Chapter 8: Arrays.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
 Character set is a set of valid characters that a language can recognise.  A character represents any letter, digit or any other sign  Java uses the.
CS-1030 Dr. Mark L. Hornick 1 C++ Language Basic control statements and data types.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1.2 Primitive Data Types and Variables
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java Part I By Wen Fei, HAO. Program Structure public class ClassName { public static void main(String[] args) { program statements } user defined methods.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Primitive Data Types. int This is the type you are familiar with and have been using Stores an integer value (whole number) between -2,147,483,648 (-2.
Basic Data Types อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 4.
Object Oriented Programming Lecture 2: BallWorld.
Java Programming Language Lecture27- An Introduction.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Topics introduced today (these topics would be covered in more detail in later classes) – Primitive Data types Variables Methods “for” loop “if-else” statement.
Fundamentals 2.
Chapter 2 Basic Computation
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Lecture 2: Data Types, Variables, Operators, and Expressions
Control Structures.
Object Oriented Programming
Introduction to Programming in Java
Introduction to Java Programming
An Introduction to Java – Part I, language basics
An overview of Java, Data types and variables
Chapter 2: Java Fundamentals
Java Programming Language
Java Basics Data Types in Java.
Names of variables, functions, classes
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

Java Programming Java Basics

Data Types Java has two main categories of data types: –Primitive data types Built in data types Many very similar to C++ (int, double, char, etc.) Variables holding primitive data types always hold the actual value, never a reference –Reference data types Arrays and user defined data types (i.e. Classes, Interfaces) Can only be accessed through reference variables

Primitive Data Types Integer data types –byte – 8 bits (values from -128 to +127) –short – 16 bits ( to ) –int – 32 bits (very big numbers) –long – 64 bits (even bigger numbers) Characters –char – 16 bits, represented in unicode, not ASCII! Floating point data types –float – 4 bytes (-3.4 x to +3.4 x ) –double – 8 bytes (-1.7 x to 1.7 x ) Boolean data –boolean can only have the value true or false Unlike C++, cannot be cast to an int (or any other data type)

Operators Arithmetic –+,-,*,/,%,++,-- Logic –&,|,^,~, >,>>> Assignment –=, +=, -=, etc.. Comparison –,>=,==,!= Work just like in C++, except for special String support

Comparison Operators Note about comparison operators –Work just as you would expect for primitive data types –We will see that they do not always operate as you would think for reference data types

Control Structures if/else, for, while, do/while, switch Basically work the same as in C/C++ if(a > 3) { a = 3; } else { a = 0; } for(i = 0; i < 10; i++) { a += i; } i = 0; while(i < 10) { a += i; i++; } i = 0; do { a += i; i++; } while(i < 10); switch(i) { case 1: string = “foo”; case 2: string = “bar”; default: string = “”; }

Java also has support for continue and break keywords Again, work very similar to C/C++ Also note: switch statements require the condition variable to be a char, byte, short or int Control Structures for(i = 0; i < 10; i++) { a += i; if(a > 100) break; } for(i = 0; i < 10; i++) { if(i == 5) continue; a += i; }

Reference Data Types Key difference between primitive and reference data types is how they are represented Primitive type variables hold the actual value of the variable Reference type variables hold the value of a reference to the object

Variable declarations: Memory representation: Example int primitive = 5; String reference = “Hello”; 5 primitive reference Hello

Arrays In Java, arrays are reference data types You can define an array of any data type (primitive or reference type) Special support built into the language for accessing information such as the length of an array Automatic bound checking at run time

Declare array variables: This just creates the references You must explicitly create the array object in order to use it Declaring Array Variables int myNumbers[]; String myStrings[];

Create array objects: In the creation of any reference data object, the new operator is almost always used –String objects can be created from String literals as we’ve seen –Array objects can also be created using Array literals Note: in the first example, myStrings is a reference to an array of references Creating Array Objects myNumbers = new int[10]; myStrings = new String[10]; myNumbers = {1, 2, 3, 4, 5};

Accessing Array Elements Just like in C/C++ Arrays also have a special length field which can be accessed to determine the size of an array myNumbers[0] = 5; myStrings[4] = “foo”; for(int i = 0; i < myNumbers.length; i++) myNumbers[i] = i;

Wrapper Classes Each primitive data type has a corresponding “Wrapper Class” reference data type Can be used to represent primitive data values as reference objects when it is necessary to do so Byte, Short, Integer, Long, Float, Double, Boolean, Character

What are classes? User defined data types Classes can contain –Fields: variables that store information about the object (can be primitive or reference variables) –Methods: functions or operations that you can perform on a data object

Example Each instance of a Circle object contains the fields and methods shown static –The static keyword signifies that the class contains only one copy of a given member variable –Non static member variables have their own copy per instance of the class public class Circle { static final double PI = 3.14; double radius; public double area() {... } public double circumference() {... }

Example System.out.println(“Hello World”); Built in Java class Static member variable (field) of the System class: PrintStream object that points to standard out Member method of the PrintStream class

Back to our Wrappers Each wrapper class contains a number of methods and also static methods that are potentially useful Examples: –Character.toLowerCase(ch) –Character.isLetter(ch) See the Java API for more details: – html

Strings In Java, Strings are reference data types They are among many built-in classes in the Java language (such as the wrapper classes) –However, they do not work exactly like all classes –Additional support is built in for them such as String operators and String literals

As mentioned before, creating reference objects in Java requires the use of the new operator Strings can be created this way: However, String literals can also be used Creating Strings String myString = new String(“foo”); String myString = “foo”;

String Operators The + operator contains special support for String data types: And also the += operator: myString = “foo” + “bar”; myString = “foo”; myString += “bar”;

Comparing Strings As mentioned before, the == operator does not always work as expected with reference data types Example: Evaluates to true iff string1 and string2 both contain a reference to the same memory location String string1 = “foo”; String string2 = string1; if(string1 == string2) System.out.println(“Yes”);

Solution The String class contains built in methods that will compare the two strings rather than the two references: String string1 = “foo”; String string2 = string1; if(string1.equals(string2)) System.out.println(“Yes”); String string1 = “foo”; String string2 = string1; if(string1.equalsIgnoreCase(string2)) System.out.println(“Yes”);

Returns a negative integer when string1 is “alphabetically” before string2 Note: “alphabetically” means we are considering the unicode value of a character The character with the smaller unicode value is considered to come first More String comparison string1.compareTo(string2);

Returns a Character reference object (not a char primitive variable) Throws a StringIndexOutOfBoundsException if given an index value that is not within the range of the length of the string –We will see more on exceptions later –For now you do not need to worry about this Accessing String characters string1.charAt(0);

Other useful String methods See more at the Java API site – html string1.length(); string1.indexOf(‘a’); string1.substring(5); string1.substring(5,8); string1.toCharArray(); string1.toUpperCase();.

StringTokenizer String text = “To be or not to be”; StringTokenizer st = new StringTokenizer(); While(st.hasMoreTokens()) { System.out.println(“The next word is “ + st.nextToken()); } Can be used to split strings into “tokens” using a fixed delimiter Default delimiter is a space Can also specify custom delimiters Must import java.util.StringTokenizer

Homework 1 Homework 1 is posted on the course website Due Feb. 2 at 11:55 PM Submit via WebCT WebCT discussion boards are up

ที่มา Rensselaer Polytechnic Institute: Owen Kellett