CORE JAVA 1.6 1 C LASS Class is a template for multiple objects with similar features and It is a blue print for objects. It defines.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
ITEC200 – Week03 Inheritance and Class Hierarchies.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
J AVA AND V ARIABLES. O VERVIEW Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
L EC. 02: D ATA T YPES AND O PERATORS (1/2) Fall Java Programming.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
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.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
VARIABLES AND TYPES CITS1001. Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Scope.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
The Java Programming Language
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
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 BASICS Prepared by The Smartpath Information Systems
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
 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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Copyright Curt Hill Variables What are they? Why do we need them?
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
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. 
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Basic Data Types อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 4.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
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.
OOP: Encapsulation &Abstraction
JAVA MULTIPLE CHOICE QUESTION.
Chapter 4 Assignment Statement
Java Primer 1: Types, Classes and Operators
Internet and Java Foundations, Programming and Practice
Chapter 3: Using Methods, Classes, and Objects
University of Central Florida COP 3330 Object Oriented Programming
Chapter 3 Assignment Statement
Chapter 3 Introduction to Classes, Objects Methods and Strings
Starting JavaProgramming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Object Oriented Programming in java
Java Programming Language
Java Basics Data Types in Java.
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

CORE JAVA

C LASS Class is a template for multiple objects with similar features and It is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Classes are the fundamental units in an object- oriented programming. We use a class to create objects( instances ). Each instance carries its own data. 2 ClassInstance Rubber stampStamped image Photographic negativePrinted photo

O BJECT Instance of class. Have its own state. Have access to all the behaviors of the class. 3

S TATE Instance variables Attributes of class 4

B EHAVIOR Methods in class Functionalities of object. 5

O BJECT C LASS All classes in Java TM technology are directly or indirectly derived from the Object class. Some of the subclasses of Object class are - Boolean, Number, Void, Math, String, StringBuffer etc. 6

I DENTIFIER Three important points to be noted about identifiers. Legal Identifiers Naming Rules Code Conventions Coding Standards Java Beans Naming Standards. 7

L EGAL I DENTIFIER Start with a letter, a currency symbol($) or connecting characters( _ ). Don’t use keywords. Case sensitive. Example 8 LegalIllegal int _a;int :b; int _____2_w;int -b; int $c;int e#; int _$;int.f; int 7g;

J AVA K EYWORDS abstractbooleanbreakcontinue charclassconstfinal doubleelseextendsimplements forgotoifnative intinterfacelongreturn privateprotectedpublicsynchronized strictfpsuperswitchvoid throwstransienttrycase assertenumbytedefault finallyimportnewshort thisvolatilecatchdo floatinstanceofpackagestatic throwwhile 9

S OURCE F ILE D ECLARATION R ULES Only one public class per source file. Comments can appear any where in tile. Public class name should be the filename. Java is a package centric language so the package declaration should be the first line. A file belongs to only one package. Import should be given after package declaration. A file can contain more than one non-public class. File with no public class can have a file name does not match any of the classes in the file. 10

C LASS D ECLARATIONS AND M ODIFIERS Modifiers Access Modifiers public private protected default Non-Access Modifiers final abstract strictfp 11

D EFAULT OR P ACKAGE L EVEL A CCESS A Class can use public and default access modifiers only. Has no modifier proceeding in the declaration. 12

D EFAULT OR P ACKAGE L EVEL A CCESS Default access in method level. 13

P UBLIC A CCESS All classes from all packages can access to the public class. ie all class in Java Universe can have access to public class. Three ways to access a method Invoking a method declared in the same class. Invoking a method using a reference of the class. Invoking an inherited method. 14

P RIVATE A CCESS Members marked private can’t be accessed by code in any class other than the class in which the private members is declared. 15

P ROTECTED A CCESS Protected and default are almost identical with one difference ie protected member can have access to other package classes (through inheritance) 16

A CCESS M ODIFIERS VisibilityPublicProtectedPrivateDefault Same ClassYes Any Class of Same packYes NoYes Subclass in same packYes NoYes Subclass outside same pack Yes inheritance No Not subclass outside pack YesNo 17

N ON – A CCESS M ODIFIERS final abstract transient synchronized native – Platform dependent. strictfp – IEEE 754 static. 18

V ARIABLE D ECLARATIONS Primitive Variables: Variables with primitive data types such as int or long. Stores data in the actual memory location of where the variable is present Reference Variables: Variables that store the address in the memory location Points to another memory location where the actual data is present 19

P RIMITIVE V ARIABLES TypeBitsBytesMin RangeMax Range byte short int long float324n/a double648n/a 20 Char 16 bit Unicode Boolean True or false.

I NSTANCE V ARIABLE D ECLARATIONS Defined inside class and outside methods. Initialized when the class is instantiated. Can use any access level. Can be marked as final transient static volatile 21

L OCAL V ARIABLE D ECLARATIONS Variable declaration within a method. Declared, initialized inside the method ie the life time of local variable will be inside method. Local variable will be on stack not on heap. In case of reference variable it will be created in heap not in stack. Can not be marked as public transient volatile abstract static. Compiler reject if any local variable has not been assigned a value. If local and instance variable has same name we call it as shadowing. 22

A RRAY D ECLARATIONS Object that store multiple variables of the same type. Can hold primitives or references Array will be as an object on the heap. 23 Examples int[ ] key; // recommended int key[ ]; // less readable String [ ] [ ] [ ] name; String [ ] manager[ ]; int [5] scores; // not legal.

F INAL V ARIABLES Makes it impossible to reinitialize once it has been initialized with an explicit value.(not default value) For primitive Once a variable is assigned a value it can’t be altered. For Reference Data within the object can be modified. Reference variable cannot be changed. 24

T RANSIENT V ARIABLES If a variable is declared as transient means we are telling the JVM to skip serialization for particular object. Serialization means writing objects state into streams. 25

V OLATILE V ARIABLES Tells the JVM that a thread accessing the variable must always have its won private copy of the variable with master copy in memory. Only applied to instance variable. 26

S TATIC V ARIABLES Create variables independent of any instance. Static members exits before making a new instance of class. Only one copy of static member regardless of member variable. Area to use Methods Variables Inner classes Initialization Blocks Not to use in Constructors Classes Interfaces Method local inner classes Inner class methods and variables Local variables. 27

E NUMS Should be declared as separate class or a class member not inside methods. Enum cannot be private or protected. Equalent Java Class Never invoke an enum directly Constructor overloading is also possible in enum 28

E NUMS 29

E NUMS 30

E NUMS 31

E NCAPSULATION Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code. 32

E NCAPSULATION 33

C ONSTRUCTOR Objects are constructed with the help of constructors. You cannot make a new object without constructor. Constructors are the code that runs whenever you use the keyword new. Every class including abstract class must have a constructor. Typically constructors are used to initialize instance variables. Two Key Points No return type Name should be same as class 34

R ULES F OR C ONSTRUCTOR Can use any access modifier Must match the name of the class Must not have a return type If you don’t type a constructor a default constructor will be automatically generated by the compiler The default constructor is always a no-args constructor. Every constructor has its first statement either this() ->overloaded constructor super() ->super class constructor Interface don’t have constructor Abstract class have constructor that activates in concrete class. Don’t call a constructor inside any methods. 35

D ETERMINE W HETHER D EFAULT C ONSTRUCTOR W ILL B E C REATED 36 No! Yes!

C HECK W HETHER L EGAL I N C ONSTRUCTORS 37 Legal ! IlLegal !

S TATIC V ARIABLES & M ETHODS In static variable or method the behavior has no dependency on its instance. Variables or methods declared as static belongs to class not to particular instance. We can use static method or variable without instance of class. Non static instance variable cannot be referenced inside static methods because there is no instance. 38

S TATIC V ARIABLES & M ETHODS If the same program written without static Here the JVM does not know about frogCount as it is not static. 39

A CCESSING S TATIC V ARIABLES & M ETHODS 40

C HECK W HETHER L EGAL I N S TATICS 41

L ITERAL V ALUES F OR A LL P RIMITIVES 42

I NTEGER L ITERALS 43 Three ways to represent integer values in Java Decimal ( base 10 ) Octal ( base 8 ) Hexadecimal ( base 16 ) Decimal Literal Normal integers Octal Integers Use only digits 0 to 7 We can have up to 21 digits in an octal number not including the leading 0

I NTEGER L ITERALS 44 Hexadecimal Literal Constructed using 16 digit symbols Numbers ( 0 to 9 ) Alphabets ( a to f ) All integer literals are defined in int but they can be used in long with the suffix “F”

F LOATING P OINT L ITERALS 45 Floating points are defined as a number, a decimal and more numbers specifying fraction.

B OOLEAN AND C HARACTER L ITERALS 46 Boolean Literal Can hold true or false. Character Literal Characters are 16 bit unsigned integers It fill fit unsigned int range ( or less )

P RIMITIVE C ASTING 47 We can assign a primitive by value and result of an expression with the help of assignment operator. Casting lets you convert primitive values from one type to another. Types of casting Implicit Explicit Implicit Casting Done by the compiler If we assign a byte value into int implicit casting is done.

P RIMITIVE C ASTING 48 Explicit Casting Look at the following example Rule : Result of an expression involving anything int-sized or smaller is always int. Ex, Multiply int and short gives an int. Divide short and byte gives an int.

P RIMITIVE C ASTING 49 Casting Saying the JVM I am responsible for any data loss while placing it here. Why we need casting in this example ? Byte can hold only up to 127 and here it is 128 Then How come -126 ? Bit Value of 128 is As 128 is greater than 127 it’s a integer. Integer has 32 bit so add 24 bits Once after type cast remove the 24 prefix bits and we will get The left most bit is for sign To find out the value of a negative using twos complement notation Flip all of the bits and add one gives gives -128 Adding 1 in give 128 againS

A RRAY 50 Arrays are objects in java that store multiple values of same type. Declaring Array of primitives Declaring Array of References

C ONSTRUCTING A RRAY 51 Array of primitives Array of References

C ONSTRUCTING A RRAY 52 Multi dimensional Array

I NITIALIZATION B LOCKS 53

W RAPPER CLASS 54 Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances These classes will be in java.lang package Primitive typeWrapper classConstructor Arguments byteBytebyte or String shortShortshort or String intIntegerint or String longLonglong or String floatFloatfloat, double or String doubleDoubledouble or String charCharacterchar booleanBooleanboolean or String

W RAPPER CLASS 55 Class to min and max values of primitives

W RAPPER CLASS 56 Class to print default values of primitives

57

W RAPPER CLASS 58

W RAPPER CLASS – A UTO B OXING 59