Java Basics

Information about Java Basics

Published on March 9, 2009

Author: ankush85

Source: authorstream.com

Content

Java Basics : Java Basics ankush …. JAVA BASICS I : JAVA BASICS I Identifiers : Identifiers Keywords Lexical elements (or identifiers) that have a special, predefined meaning in the language Cannot be redefined or used in any other way in a program Ex: public, private, if, class, throws See p. 32 in LL for complete list Identifiers : Identifiers Other Identifiers Defined by programmer Java API defines quite a few for us e.g. System, Scanner, String, out are used to represent names of variables, methods and classes Cannot be keywords We could redefine those defined in Java API if we wanted to, but this is generally not a good idea Java IDs must begin with a letter, followed by any number of letters, digits, _ (underscore) or $ characters Similar to identifier rules in most programming langs Identifiers : Identifiers Important Note: Java identifiers are case-sensitive – this means that upper and lower case letters are considered to be different – be careful to be consistent! Ex: ThisVariable and thisvariable are NOT the same Naming Convention: Many Java programmers use the following conventions: Classes: start with upper case, then start each word with an upper case letter Ex: StringBuffer, BufferedInputStream, ArrayIndexOutOfBoundsException Methods and variables: start with lower case, then start each word with an upper case letter Ex: compareTo, lastIndexOf, mousePressed Literals : Literals Values that are hard-coded into a program They are literally in the code! Different types have different rules for specifying literal values They are fairly intuitive and similar across most programming languages Integer An optional +/- followed by a sequence of digits Ex: 1024, -78, 1024786074 Character A single character in single quotes Ex: ‘a’, ‘y’, ‘q’ String A sequence of characters contained within double quotes Ex: “This is a string literal” See p. 75-77 for more literals Statements : Statements Units of declaration or execution A program execution can be broken down into execution of the program’s individual statements Every Java statement must be terminated by a semicolon (;) Variable declaration statement <type> <variable>, <variable>, …; Ex: int var1, var2; Assignment statement <variable> = <expression>; Ex. var1 = 100; var2 = 100 + var1; Method call <method ID>(<expression>,<expression>,...); System.out.println(“Answer is “ + var1); We’ll discuss others later Variables : Variables Memory locations that are associated with identifiers Values can change throughout the execution of a program In Java, must be specified as a certain type or class The type of a variable specifies its properties: the data it can store and the operations that can be performed on it Ex: int type: discuss Java is fairly strict about enforcing data type values You will get a compilation error if you assign an incorrect type to a variable: Ex: int i = “hello”; incompatible types found: java.lang.String required: int int i = "hello"; ^ Variables : Variables Note: For numeric types, you even get an error if the value assigned will “lose precision” if placed into the variable Generally speaking this means we can place “smaller” values into “larger” variables but we cannot place “larger” values into “smaller” variables Ex: byte < short < int < long < float < double Ex: int i = 3.5; possible loss of precision found : double required: int int i = 3.5; ^ Ex: double x = 100; This is ok Variables : Variables Floating point literals in Java are by default double If you assign one to a float variable, you will get a “loss of precision error” as shown in the previous slide If you want to assign a “more precise” value to a “less precise” variable, you must explicitly cast the value to that variable type int i = 5; int j = 4.5; float x = 3.5; float y = (float) 3.5; double z = 100; i = z; y = z; z = i; j = (long) y; j = (byte) y; Error check each of the statements in the box to the right Variables : Variables In Java, variables fall into two categories: Primitive Types Simple types whose values are stored directly in the memory location associated with a variable Ex: int var1 = 100; There are 8 primitive types in Java: byte, short, int, long, float, double, char, boolean See Section 2.3 and ex2a.java for more details on the primitive numeric types var1 100 Variables : Variables Reference Types (or class types) Types whose values are references to objects that are stored elsewhere in memory Ex: String s = new String(“Hello There”); There are many implications to using reference types, and we must use them with care Different objects have different capabilities, based on their classes We will discuss reference types in more detail in Chapter 3 when we start looking at Objects s Hello There Variables : Variables In Java, all variables must be declared before they can be used Ex: x = 5.0; This will cause an error unless x has previously been declared as a double variable Java variables can be initialized in the same statement in which they are declared Ex: double x = 5.0; Multiple variables of the same type can be declared and initialized in a single statement, as long as they are separated by commas Ex: int i = 10, j = 20, k = 45; cannot resolve symbol symbol : variable x location : class classname x = 5.0; ^ Operators and Expressions : Operators and Expressions Expressions are parts of statements that Describe a set of operations to be performed Are evaluated at run time Ultimately result in a single value, the result of the computation Result replaced the expression in the statement Ex: Consider the assignment statement : x=1+2+3+4; 1+2+3+4 is evaluated to be 10 when the program is run X ultimately gets assigned the value 10 Operators describe the operations that should be done Simple numeric operations Other more advanced operations Operators and Expressions : Operators and Expressions Numeric operators in Java include +, –, *, /, % These are typical across most languages A couple points, however: If both operands are integer, / will give integer division, always producing an integer result – discuss implications The % operator was designed for integer operands and gives the remainder of integer division However, % can be used with floating point as well int i, j, k, m; i = 16; j = 7; k = i / j; // answer? m = i % j; // answer? Operators and Expressions : Operators and Expressions Precedence and Associativity See chart on p. 81 and on p. 678 Recall that the precedence indicates the order in which operators are applied Recall that the associativity indicates the order in which operands are accessed given operators of the same precedence General guidelines to remember for arithmetic operators: *, /, % same precedence, left to right associativity +, – same (lower) precedence, also L to R Ok, let’s do another example ex2a.java Operators and Expressions : Operators and Expressions Java has a number of convenience operators Allow us to do operations with less typing Ex: X = X + 1; X++; Y = Y – 5; Y –= 5; See Sections 2.11 and 2.12 for more details One point that should be emphasized is the difference between the prefix and postfix versions of the unary operators What is the difference between the statements: X++; ++X; References : References What do we mean by “references”? The data stored in a variable is just the “address” of the location where the object is stored Thus it is separate from the object itself Ex: If I have a Contacts file on my PC, it will have the address of my friend, Joe Schmoe (stored as Schmoe, J.) I can use that address to send something to Joe or to go visit him if I would like However, if I change that address in my Contacts file, it does NOT in any way affect Joe, but now I no longer know where Joe is located However, I can indirectly change the data in the object through the reference Knowing his address, I can go to Joe’s house and steal his plasma TV Using Objects : Using Objects What do we mean by "objects"? Let's first discuss classes Classes are blueprints for our data The class structure provides a good way to encapsulate the data and operations of a new type together Instance data and instance methods The data gives us the structure of the objects and the operations show us how to use them Ex: A String Using Objects : Using Objects User of the class knows the general nature of the data, and the public methods, but NOT the implementation details But does not need to know them in order to use the class Ex: BigInteger We call this data abstraction Java classes determine the structure and behavior of Java objects To put it another way, Java objects are instances of Java classes More References : More References Back to references, let's now see some of the implications of reference variables Declaring a variable does NOT create an object We must create objects separately from declaring variables StringBuffer S1, S2; Right now we have no actual StringBuffer objects – just two variables that could access them To get objects we must use the new operator or call a method that will create an object for us S1 = new StringBuffer("Hello"); S1 now references an instance of a StringBuffer object but S2 does not More References : More References So what value does S2 have? For now we will say that we should not count on it to have any value – we must initialize it before we use it If we try to access it without initializing it, we will get an error Multiple variables can access and alter the same object S2 = S1; Now any change to S1 or S2 will update the same object S1 S2 Hello More References : More References Properties of objects (public methods and public instance variables) are accessed via "dot" notation S1.append(" there Java maestros!"); S2 will also access the appended object Comparison of reference variables compares the references, NOT the objects StringBuffer S3 = new StringBuffer("Hello there Java maestros!"); if (S1 == S2) System.out.println("Equal"); // yes if (S1 == S3) System.out.println("Equal"); // no What if we want to compare the objects? More References : More References We use the equals() method This is generally defined for many Java classes to compare data within objects We will see how to define it for our own classes soon However, the equals() method is not (re)defined for the StringBuffer class, so we need to convert our StringBuffer objects into Strings in order to compare them: if (S1.toString().equals(S3.toString())) System.out.println("Same value"); // yes It seems complicated but it will make more sense when we get into defining new classes More references : More references Note the difference in the tests: The == operator shows us that it is the same object The equals method show us that the values are in some way the same (depending on how it is defined) References can be set to null to initialize or reinitialize a variable Null references cannot be accessed via the "dot" notation If it is attempted a run-time error results S1 = null; S1.append("This will not work!"); More references : More references Why? The method calls are associated with the OBJECT that is being accessed, NOT with the variable If there is no object, there are no methods available to call Result is NullPointerException – common error so remember it! Let's take a look at ex3.java Program Input : Program Input We’ve already discussed basic output with the terminal window System.out.println(“Area is “ + area); Standard Output Stream For now, we’ll get input from two sources Standard Input Stream Scanner class Command Line Arguments Streams : Streams A Stream is a continuous, seemingly infinite supply of or sink for data An ordered sequence of bytes flows in a specified direction in from some source can be sent out to some destination Acts as a pipe connected to your program A channel providing communication to and from the outside world For now, we’ll concern ourselves with the two (three) given to us Standard Input: System.in Standard Output: System.out Scanner : Scanner Scanner is a class that reads data from the standard input stream and parses it into tokens based on a delimiter A delimiter is a character or set of characters that distinguish one token from another By default the Scanner class uses white space as the delimiter The tokens can be read in either as Strings next() nextLine() Or they can be read as primitive types Ex: nextInt(), nextFloat(), nextDouble() Scanner : Scanner If read as primitive types, an error will occur if the actual token does not match what you are trying to read Ex: Please enter an int: hello Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at ex3.main(ex3.java:39) These types of errors in Java are called exceptions Java has many different exceptions We'll look at exceptions in more detail later Let’s try an example: ex4a.java ex4b.java Command Line Args : Command Line Args Remember the main() method public static void main(String[] args) args is an array of Strings corresponding to the list of arguments typed by the user when the interpreter was executed javalab$ java myProg.class 10 13 Steve Passed in by the operating system User must know the order and format of each argument NOTE: Unlike C/C++, only the actual arguments are passed to the program We’ll discuss arrays in more detail soon For now, let’s do an example: ex4c.java JAVA BASICS II : JAVA BASICS II EXPRESSIONS : EXPRESSIONS MORE EXPRESSIONS : MORE EXPRESSIONS Slide 35: class DisplayWarning { /** * Displaying a warning program by J M Bishop Aug 1996 * ---------------------------- Java 1.1 October 1997 * Illustrates the form of a program and the use of println. */ public static void main(String[] args) { System.out.println("-----------------------------"); System.out.println("| |"); System.out.println("| W A R N I N G |"); System.out.println("| Possible virus detected |"); System.out.println("| Reboot and run virus |"); System.out.println("| remover software |"); System.out.println("| |"); System.out.println("-----------------------------"); } } Slide 36: C:\heinz\examples\TestInit>java DisplayWarning ----------------------------- | | | W A R N I N G | | Possible virus detected | | Reboot and run virus | | remover software | | | ----------------------------- Slide 37: /* Interest Increase Program by J M Bishop Aug 1996 * ------------------------- Java 1.1 Oct 1997 * Calculates the difference in simple interest for two interest * rates for the remainder of the year from a given month. * * Illustrates declarations, assignment, constants, * expressions and printing. */ class InterestIncrease { static final double p = 1000; // in graz static final int m = 4; // for April static final double oldRate = 12.5; // % static final double newRate = 13.00; // % public static void main(String[] args) { // Start with a title System.out.println("SavBank Interest Calculation"); System.out.println("============================"); Slide 38: // perform the preliminary calculation double ptOver100 = p * (12 - m) / 12 / 100; // print out the results System.out.println("Given a change of interest rate from "+ oldRate+"% to "+newRate+"% in month "+m+","); System.out.println("on a principal of G"+p+ " the interest for the rest of the year"); System.out.print("will change by graz and cents: "); System.out.println(ptOver100 * newRate - ptOver100 * oldRate); } } Slide 39: C:\heinz\examples\TestInit>java InterestIncrease SavBank Interest Calculation ============================ Given a change of interest rate from 12.5% to 13.0% in month 4, on a principal of G1000.0 the interest for the rest of the year will change by graz and cents: 3.3333333333333286 Slide 40: class TemperatureTable { /* Displays a simple table converting Celsius * to Farhenheit for a given range. * * Illustrates using the loop variable * in expressions in the loop */ public static void main(String[] args) { System.out.println("Temperature Conversion Table"); System.out.println("============================"); System.out.println(); System.out.println("C F"); for (int c = 5; c <= 20; c++) { System.out.print(c+"\t"); System.out.println(Math.round(c*9/5 + 32)); } } } Slide 41: C:\abc\examples\TestInit>java TemperatureTable Temperature Conversion Table ============================ C F 5 41 6 42 7 44 8 46 9 48 10 50 11 51 12 53 13 55 14 57 15 59 16 60 17 62 18 64 19 66 20 68

Related presentations


Other presentations created by ankush85

Nanotechnology
03. 04. 2009
0 views

Nanotechnology

Human Resource Management System
06. 03. 2009
0 views

Human Resource Management System

Nanotechnology
27. 03. 2009
0 views

Nanotechnology

INTRODUCTION TO NANOTECHNOLOGY
20. 11. 2009
0 views

INTRODUCTION TO NANOTECHNOLOGY

Nanotechnology in Sports
22. 11. 2009
0 views

Nanotechnology in Sports

Computer Architecture
14. 07. 2009
0 views

Computer Architecture

HR
18. 03. 2009
0 views

HR

Hospital Management System
08. 04. 2009
0 views

Hospital Management System

Welcome to Visual Basic
06. 03. 2009
0 views

Welcome to Visual Basic

HTML
20. 04. 2009
0 views

HTML

Computer Languages
03. 06. 2013
0 views

Computer Languages

Taking Care of Computer
03. 06. 2013
0 views

Taking Care of Computer

Understanding Camera
16. 10. 2012
0 views

Understanding Camera

Photography Technical Terms
25. 09. 2012
0 views

Photography Technical Terms

Basics of Photography
25. 09. 2012
0 views

Basics of Photography

AIR MUSCLES
03. 01. 2012
0 views

AIR MUSCLES

Molecular Nanotechnology
24. 11. 2009
0 views

Molecular Nanotechnology

Nanotech Innovation
22. 11. 2009
0 views

Nanotech Innovation

FINANCIAL  MARKET
16. 05. 2009
0 views

FINANCIAL MARKET

Operating System
19. 04. 2009
0 views

Operating System

Management Control
10. 07. 2009
0 views

Management Control

Accounting Principles
01. 07. 2009
0 views

Accounting Principles

Balance Sheet
21. 07. 2009
0 views

Balance Sheet

Balance Sheet Auditing
01. 07. 2009
0 views

Balance Sheet Auditing

BRANCH AND BOUND
05. 03. 2009
0 views

BRANCH AND BOUND

THE  THREE  BRANCHES  OF GOVERNMENT
13. 06. 2009
0 views

THE THREE BRANCHES OF GOVERNMENT

Structure of Atom
11. 05. 2009
0 views

Structure of Atom

Compression Techniques
05. 03. 2009
0 views

Compression Techniques

DYNAMIC PROGRAMMING
06. 03. 2009
0 views

DYNAMIC PROGRAMMING

Quantum Mechanics
25. 08. 2009
0 views

Quantum Mechanics

Marketing Plan
19. 06. 2009
0 views

Marketing Plan

Book Keeping
24. 06. 2009
0 views

Book Keeping

DFDS
02. 10. 2008
0 views

DFDS

Semiconductors
25. 04. 2009
0 views

Semiconductors

Organic  Chemistry
28. 04. 2009
0 views

Organic Chemistry

Atoms Molecules and Ions
17. 06. 2009
0 views

Atoms Molecules and Ions

Covalent Bond
25. 04. 2009
0 views

Covalent Bond

Cost Accounting Standards
25. 06. 2009
0 views

Cost Accounting Standards

Crisis Management
19. 06. 2009
0 views

Crisis Management

Marketing
18. 03. 2009
0 views

Marketing

Business Strategy
27. 04. 2009
0 views

Business Strategy

Time Management
23. 03. 2009
0 views

Time Management

Networking Protocols
23. 05. 2009
0 views

Networking Protocols

Network Layer
23. 05. 2009
0 views

Network Layer

Final Accounts
24. 06. 2009
0 views

Final Accounts

ARTIFICIAL  INTELLIGENCE
03. 04. 2009
0 views

ARTIFICIAL INTELLIGENCE

Play with C
08. 04. 2009
0 views

Play with C

Software Development Cycle
23. 03. 2009
0 views

Software Development Cycle

THE GREEDY METHOD
06. 03. 2009
0 views

THE GREEDY METHOD

JOB SEQUENCING
06. 03. 2009
0 views

JOB SEQUENCING

Electricity and Magnetism
29. 04. 2009
0 views

Electricity and Magnetism

Optical Fiber
24. 05. 2009
0 views

Optical Fiber

Quality Assurance
06. 03. 2009
0 views

Quality Assurance

Object-oriented Design
11. 04. 2009
0 views

Object-oriented Design

A.R. Rahman
08. 03. 2009
0 views

A.R. Rahman

Hollywood Female Celebrities
13. 03. 2009
0 views

Hollywood Female Celebrities

Flow nets
04. 09. 2009
0 views

Flow nets

Energy and Nanotechnology
22. 11. 2009
0 views

Energy and Nanotechnology

LOGIC  DESIGN
06. 03. 2009
0 views

LOGIC DESIGN

VB-IDE
06. 03. 2009
0 views

VB-IDE

DLF IPL FINAL
25. 05. 2009
0 views

DLF IPL FINAL

MINIMUM SPANNING TREES
06. 03. 2009
0 views

MINIMUM SPANNING TREES

CPU Scheduling
05. 03. 2009
0 views

CPU Scheduling

Virtual Memory
05. 03. 2009
0 views

Virtual Memory

POK
09. 05. 2009
0 views

POK

2D Transformations
05. 03. 2009
0 views

2D Transformations

Greedy Algorithms
05. 03. 2009
0 views

Greedy Algorithms

BACKTRACKING
05. 03. 2009
0 views

BACKTRACKING

DIVIDE And CONQUER
06. 03. 2009
0 views

DIVIDE And CONQUER

ELEMENTARY DATA STRUCTURES
06. 03. 2009
0 views

ELEMENTARY DATA STRUCTURES

JPEG Compression
06. 03. 2009
0 views

JPEG Compression

Mpeg-compression
06. 03. 2009
0 views

Mpeg-compression

NP - HARD
06. 03. 2009
0 views

NP - HARD

TRAVELLING SALESPERSON PROBLEM
06. 03. 2009
0 views

TRAVELLING SALESPERSON PROBLEM

VBA Introduction
06. 03. 2009
0 views

VBA Introduction

Introduction to Java
09. 03. 2009
0 views

Introduction to Java

Heuristic Search
13. 03. 2009
0 views

Heuristic Search

HSM
19. 03. 2009
0 views

HSM

Tata's  Nano  Car
25. 03. 2009
0 views

Tata's Nano Car

Air Cranes
08. 04. 2009
0 views

Air Cranes

Newborn Care
10. 04. 2009
0 views

Newborn Care

Photosynthesis Process
10. 04. 2009
0 views

Photosynthesis Process

ActionScript
13. 04. 2009
0 views

ActionScript

Xml
15. 04. 2009
0 views

Xml

Snakes mis use
17. 04. 2009
0 views

Snakes mis use

Php Web Development
21. 04. 2009
0 views

Php Web Development

Cricket Intro
21. 04. 2009
0 views

Cricket Intro

Cricket Umpiring and Rules
21. 04. 2009
0 views

Cricket Umpiring and Rules

Arm and Forearm
23. 04. 2009
0 views

Arm and Forearm

Elements Ions Isotopes
25. 04. 2009
0 views

Elements Ions Isotopes

Chemical Bond
25. 04. 2009
0 views

Chemical Bond

Discovering Newtons Laws
29. 04. 2009
0 views

Discovering Newtons Laws

FreeFall
29. 04. 2009
0 views

FreeFall

Digital photography
26. 04. 2009
0 views

Digital photography

Health Effects of Alcohol
26. 04. 2009
0 views

Health Effects of Alcohol

Poetry Terminology
27. 04. 2009
0 views

Poetry Terminology

Indian Force
05. 05. 2009
0 views

Indian Force

Machine Intelligence
14. 05. 2009
0 views

Machine Intelligence

Data Link Layer
16. 05. 2009
0 views

Data Link Layer

Database Development Cycle
15. 05. 2009
0 views

Database Development Cycle

Queue
15. 05. 2009
0 views

Queue

Presentaion Skills
23. 04. 2009
0 views

Presentaion Skills

Network Layers
23. 05. 2009
0 views

Network Layers

Narmada Dam, India
23. 05. 2009
0 views

Narmada Dam, India

User Datagram Protocol
24. 05. 2009
0 views

User Datagram Protocol

Linear Momentum
28. 05. 2009
0 views

Linear Momentum

Stack and Queue
04. 06. 2009
0 views

Stack and Queue

Information Management
19. 06. 2009
0 views

Information Management

Role of Senior Management
19. 06. 2009
0 views

Role of Senior Management

Wake Up India
07. 06. 2009
0 views

Wake Up India

Adobe Flex 3.0
13. 06. 2009
0 views

Adobe Flex 3.0

Adobe Flex Presentation
13. 06. 2009
0 views

Adobe Flex Presentation

Introduction to Adobe Flex
13. 06. 2009
0 views

Introduction to Adobe Flex

Adobe Flash Media Server
13. 06. 2009
0 views

Adobe Flash Media Server

Dreamweaver
13. 06. 2009
0 views

Dreamweaver

Adobe Flash
13. 06. 2009
0 views

Adobe Flash

Flash CS4 Professional
13. 06. 2009
0 views

Flash CS4 Professional

Adobe Flash Lite
13. 06. 2009
0 views

Adobe Flash Lite

Digital Camera
13. 06. 2009
0 views

Digital Camera

Mozilla_Firefox
15. 06. 2009
0 views

Mozilla_Firefox

Managerial Accounting
27. 06. 2009
0 views

Managerial Accounting

Accounting  Information  System
01. 07. 2009
0 views

Accounting Information System

RETAILING AND MARKETING
06. 07. 2009
0 views

RETAILING AND MARKETING

ACCOUNTING IN BUSINESS
05. 07. 2009
0 views

ACCOUNTING IN BUSINESS

STRATEGIC RETAIL MANAGEMENT
05. 07. 2009
0 views

STRATEGIC RETAIL MANAGEMENT

Reiki
01. 08. 2009
0 views

Reiki

Using Buttons in PowerPoint
26. 04. 2009
0 views

Using Buttons in PowerPoint

Nanotechnology  for  Students
21. 08. 2009
0 views

Nanotechnology for Students

NANOSCIENCE
25. 08. 2009
0 views

NANOSCIENCE

Fundamentals of Nanoscience
27. 08. 2009
0 views

Fundamentals of Nanoscience

Nanoscience in Nature
27. 08. 2009
0 views

Nanoscience in Nature

Applied Mechanics
04. 09. 2009
0 views

Applied Mechanics

Accounts Payable Training
27. 06. 2009
0 views

Accounts Payable Training