SlideShare uma empresa Scribd logo
1 de 30
Java Basics
Brandon Black
CS401
Slides adapted from Silver Webbuzz
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
• 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
– 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
• 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
• 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
• 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
– 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
– 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
• 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
• 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
• 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
• 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 (to be discussed later)
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
– 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
• 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
– 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
• 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
– 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
• 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
• 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
– 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
• 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
• 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
• 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
• 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
• 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 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
– 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
• 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

Mais conteúdo relacionado

Mais procurados

Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...Edureka!
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPTAjay Chimmani
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java Ravi_Kant_Sahu
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)Jadavsejal
 
Constructor in java
Constructor in javaConstructor in java
Constructor in javaHitesh Kumar
 

Mais procurados (20)

Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Java packages
Java packagesJava packages
Java packages
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
java Features
java Featuresjava Features
java Features
 
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
JVM
JVMJVM
JVM
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
OOP java
OOP javaOOP java
OOP java
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 

Destaque

Destaque (20)

Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
PALASH SL GUPTA
PALASH SL GUPTAPALASH SL GUPTA
PALASH SL GUPTA
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Introduction to basics of java
Introduction to basics of javaIntroduction to basics of java
Introduction to basics of java
 
Java basics
Java basicsJava basics
Java basics
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Java basics
Java basicsJava basics
Java basics
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
Java Basics
Java BasicsJava Basics
Java Basics
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Java basics part 1
Java basics part 1Java basics part 1
Java basics part 1
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Ppt on java basics
Ppt on java basicsPpt on java basics
Ppt on java basics
 

Semelhante a Java Basics

cs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptxcs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptxmshanajoel6
 
Java class 1
Java class 1Java class 1
Java class 1Edureka!
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with javaHawkman Academy
 
Java Closures
Java ClosuresJava Closures
Java ClosuresBen Evans
 
data-types-operators-datatypes-operators.ppt
data-types-operators-datatypes-operators.pptdata-types-operators-datatypes-operators.ppt
data-types-operators-datatypes-operators.pptGagan Rana
 
Java Script
Java ScriptJava Script
Java ScriptSarvan15
 
Java Script
Java ScriptJava Script
Java ScriptSarvan15
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8 Bansilal Haudakari
 
Adobe Flash Actionscript language basics chapter-2
Adobe Flash Actionscript language basics chapter-2Adobe Flash Actionscript language basics chapter-2
Adobe Flash Actionscript language basics chapter-2Nafis Ahmed
 

Semelhante a Java Basics (20)

cs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptxcs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptx
 
Java class 1
Java class 1Java class 1
Java class 1
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Java
JavaJava
Java
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with java
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
java
java java
java
 
data-types-operators-datatypes-operators.ppt
data-types-operators-datatypes-operators.pptdata-types-operators-datatypes-operators.ppt
data-types-operators-datatypes-operators.ppt
 
Java basics training 1
Java basics training 1Java basics training 1
Java basics training 1
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
 
Adobe Flash Actionscript language basics chapter-2
Adobe Flash Actionscript language basics chapter-2Adobe Flash Actionscript language basics chapter-2
Adobe Flash Actionscript language basics chapter-2
 
Java basic
Java basicJava basic
Java basic
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 

Último

10 Best WordPress Plugins to make the website effective in 2024
10 Best WordPress Plugins to make the website effective in 202410 Best WordPress Plugins to make the website effective in 2024
10 Best WordPress Plugins to make the website effective in 2024digital learning point
 
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书zdzoqco
 
How to Empower the future of UX Design with Gen AI
How to Empower the future of UX Design with Gen AIHow to Empower the future of UX Design with Gen AI
How to Empower the future of UX Design with Gen AIyuj
 
Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Rndexperts
 
Niintendo Wii Presentation Template.pptx
Niintendo Wii Presentation Template.pptxNiintendo Wii Presentation Template.pptx
Niintendo Wii Presentation Template.pptxKevinYaelJimnezSanti
 
Unit1_Syllbwbnwnwneneneneneneentation_Sem2.pptx
Unit1_Syllbwbnwnwneneneneneneentation_Sem2.pptxUnit1_Syllbwbnwnwneneneneneneentation_Sem2.pptx
Unit1_Syllbwbnwnwneneneneneneentation_Sem2.pptxNitish292041
 
Iconic Global Solution - web design, Digital Marketing services
Iconic Global Solution - web design, Digital Marketing servicesIconic Global Solution - web design, Digital Marketing services
Iconic Global Solution - web design, Digital Marketing servicesIconic global solution
 
DAKSHIN BIHAR GRAMIN BANK: REDEFINING THE DIGITAL BANKING EXPERIENCE WITH A U...
DAKSHIN BIHAR GRAMIN BANK: REDEFINING THE DIGITAL BANKING EXPERIENCE WITH A U...DAKSHIN BIHAR GRAMIN BANK: REDEFINING THE DIGITAL BANKING EXPERIENCE WITH A U...
DAKSHIN BIHAR GRAMIN BANK: REDEFINING THE DIGITAL BANKING EXPERIENCE WITH A U...Rishabh Aryan
 
Making and Unmaking of Chandigarh - A City of Two Plans2-4-24.ppt
Making and Unmaking of Chandigarh - A City of Two Plans2-4-24.pptMaking and Unmaking of Chandigarh - A City of Two Plans2-4-24.ppt
Making and Unmaking of Chandigarh - A City of Two Plans2-4-24.pptJIT KUMAR GUPTA
 
The spirit of digital place - game worlds and architectural phenomenology
The spirit of digital place - game worlds and architectural phenomenologyThe spirit of digital place - game worlds and architectural phenomenology
The spirit of digital place - game worlds and architectural phenomenologyChristopher Totten
 
10 must-have Chrome extensions for designers
10 must-have Chrome extensions for designers10 must-have Chrome extensions for designers
10 must-have Chrome extensions for designersPixeldarts
 
General Knowledge Quiz Game C++ CODE.pptx
General Knowledge Quiz Game C++ CODE.pptxGeneral Knowledge Quiz Game C++ CODE.pptx
General Knowledge Quiz Game C++ CODE.pptxmarckustrevion
 
group_15_empirya_p1projectIndustrial.pdf
group_15_empirya_p1projectIndustrial.pdfgroup_15_empirya_p1projectIndustrial.pdf
group_15_empirya_p1projectIndustrial.pdfneelspinoy
 
Color Theory Explained for Noobs- Think360 Studio
Color Theory Explained for Noobs- Think360 StudioColor Theory Explained for Noobs- Think360 Studio
Color Theory Explained for Noobs- Think360 StudioThink360 Studio
 
guest bathroom white and blue ssssssssss
guest bathroom white and blue ssssssssssguest bathroom white and blue ssssssssss
guest bathroom white and blue ssssssssssNadaMohammed714321
 
guest bathroom white and bluesssssssssss
guest bathroom white and bluesssssssssssguest bathroom white and bluesssssssssss
guest bathroom white and bluesssssssssssNadaMohammed714321
 
cda.pptx critical discourse analysis ppt
cda.pptx critical discourse analysis pptcda.pptx critical discourse analysis ppt
cda.pptx critical discourse analysis pptMaryamAfzal41
 
Karim apartment ideas 01 ppppppppppppppp
Karim apartment ideas 01 pppppppppppppppKarim apartment ideas 01 ppppppppppppppp
Karim apartment ideas 01 pppppppppppppppNadaMohammed714321
 
Piece by Piece Magazine
Piece by Piece Magazine                      Piece by Piece Magazine
Piece by Piece Magazine CharlottePulte
 
Karim apartment ideas 02 ppppppppppppppp
Karim apartment ideas 02 pppppppppppppppKarim apartment ideas 02 ppppppppppppppp
Karim apartment ideas 02 pppppppppppppppNadaMohammed714321
 

Último (20)

10 Best WordPress Plugins to make the website effective in 2024
10 Best WordPress Plugins to make the website effective in 202410 Best WordPress Plugins to make the website effective in 2024
10 Best WordPress Plugins to make the website effective in 2024
 
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
 
How to Empower the future of UX Design with Gen AI
How to Empower the future of UX Design with Gen AIHow to Empower the future of UX Design with Gen AI
How to Empower the future of UX Design with Gen AI
 
Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025
 
Niintendo Wii Presentation Template.pptx
Niintendo Wii Presentation Template.pptxNiintendo Wii Presentation Template.pptx
Niintendo Wii Presentation Template.pptx
 
Unit1_Syllbwbnwnwneneneneneneentation_Sem2.pptx
Unit1_Syllbwbnwnwneneneneneneentation_Sem2.pptxUnit1_Syllbwbnwnwneneneneneneentation_Sem2.pptx
Unit1_Syllbwbnwnwneneneneneneentation_Sem2.pptx
 
Iconic Global Solution - web design, Digital Marketing services
Iconic Global Solution - web design, Digital Marketing servicesIconic Global Solution - web design, Digital Marketing services
Iconic Global Solution - web design, Digital Marketing services
 
DAKSHIN BIHAR GRAMIN BANK: REDEFINING THE DIGITAL BANKING EXPERIENCE WITH A U...
DAKSHIN BIHAR GRAMIN BANK: REDEFINING THE DIGITAL BANKING EXPERIENCE WITH A U...DAKSHIN BIHAR GRAMIN BANK: REDEFINING THE DIGITAL BANKING EXPERIENCE WITH A U...
DAKSHIN BIHAR GRAMIN BANK: REDEFINING THE DIGITAL BANKING EXPERIENCE WITH A U...
 
Making and Unmaking of Chandigarh - A City of Two Plans2-4-24.ppt
Making and Unmaking of Chandigarh - A City of Two Plans2-4-24.pptMaking and Unmaking of Chandigarh - A City of Two Plans2-4-24.ppt
Making and Unmaking of Chandigarh - A City of Two Plans2-4-24.ppt
 
The spirit of digital place - game worlds and architectural phenomenology
The spirit of digital place - game worlds and architectural phenomenologyThe spirit of digital place - game worlds and architectural phenomenology
The spirit of digital place - game worlds and architectural phenomenology
 
10 must-have Chrome extensions for designers
10 must-have Chrome extensions for designers10 must-have Chrome extensions for designers
10 must-have Chrome extensions for designers
 
General Knowledge Quiz Game C++ CODE.pptx
General Knowledge Quiz Game C++ CODE.pptxGeneral Knowledge Quiz Game C++ CODE.pptx
General Knowledge Quiz Game C++ CODE.pptx
 
group_15_empirya_p1projectIndustrial.pdf
group_15_empirya_p1projectIndustrial.pdfgroup_15_empirya_p1projectIndustrial.pdf
group_15_empirya_p1projectIndustrial.pdf
 
Color Theory Explained for Noobs- Think360 Studio
Color Theory Explained for Noobs- Think360 StudioColor Theory Explained for Noobs- Think360 Studio
Color Theory Explained for Noobs- Think360 Studio
 
guest bathroom white and blue ssssssssss
guest bathroom white and blue ssssssssssguest bathroom white and blue ssssssssss
guest bathroom white and blue ssssssssss
 
guest bathroom white and bluesssssssssss
guest bathroom white and bluesssssssssssguest bathroom white and bluesssssssssss
guest bathroom white and bluesssssssssss
 
cda.pptx critical discourse analysis ppt
cda.pptx critical discourse analysis pptcda.pptx critical discourse analysis ppt
cda.pptx critical discourse analysis ppt
 
Karim apartment ideas 01 ppppppppppppppp
Karim apartment ideas 01 pppppppppppppppKarim apartment ideas 01 ppppppppppppppp
Karim apartment ideas 01 ppppppppppppppp
 
Piece by Piece Magazine
Piece by Piece Magazine                      Piece by Piece Magazine
Piece by Piece Magazine
 
Karim apartment ideas 02 ppppppppppppppp
Karim apartment ideas 02 pppppppppppppppKarim apartment ideas 02 ppppppppppppppp
Karim apartment ideas 02 ppppppppppppppp
 

Java Basics

  • 1. Java Basics Brandon Black CS401 Slides adapted from Silver Webbuzz
  • 2. 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
  • 3. 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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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"; ^
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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; ^
  • 13. 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 (to be discussed later)
  • 14. 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?
  • 15. 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
  • 16. 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;
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 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
  • 22. 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?
  • 23. 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
  • 24. 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!");
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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()
  • 29. 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
  • 30. 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

Notas do Editor

  1. Ex: int type: can store values -2147483648 to 2147483647 Has operations +, –, *, /, % Study of various data types is a large part of the CS 0445 Data Structures course (blatant plug for CS 0445)