Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

Hellomessage Variable Is Declared As A Local Variable:: Public Class Public Static Void

The document discusses several Java concepts including: 1. Declaring and initializing variables of different types like strings, integers, and booleans. 2. Using variables in expressions, conditionals, and loops. 3. Defining classes with fields and methods. 4. Creating objects from classes and calling methods on those objects.

Uploaded by

Ayyappa Raj
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Hellomessage Variable Is Declared As A Local Variable:: Public Class Public Static Void

The document discusses several Java concepts including: 1. Declaring and initializing variables of different types like strings, integers, and booleans. 2. Using variables in expressions, conditionals, and loops. 3. Defining classes with fields and methods. 4. Creating objects from classes and calling methods on those objects.

Uploaded by

Ayyappa Raj
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

helloMessage variable is declared as a local variable:

public class MainClass { public static void main(String[] args) { String helloMessage; helloMessage = "Hello, World!"; System.out.println(helloMessage); } }

shows the proper way to declare a class variable named helloMessa


public class MainClass { static String helloMessage; public static void main(String[] args) { helloMessage = "Hello, World!"; System.out.println(helloMessage); } }

Demonstrate lifetime of a variable


public class MainClass { public static void main(String args[]) { int x; for (x = 0; x < 3; x++) { int y = -1; // y is initialized each time block is entered System.out.println("y is: " + y); // this always prints -1 y = 100; System.out.println("y is now: " + y); } } }

y y y y y y

is: -1 is now: 100 is: -1 is now: 100 is: -1 is now: 100

Variable Dynamic Initialization


public class MainClass { public static void main(String args[]) { double a = 3.0, b = 4.0; // c is dynamically initialized double c = Math.sqrt(a * a + b * b); System.out.println("Hypotenuse is " + c); } }

Hypotenuse is 5.0

Display all command-line arguments.


class CommandLine { public static void main(String args[]) { for (int i = 0; i < args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } }

Java boolean value


public class Main { public static void main(String[] args) { boolean b1 = true; boolean b2 = false; boolean b3 = (10 > 2) ? true : false; System.out.println("Value of boolean variable b1 is :" + b1); System.out.println("Value of boolean variable b2 is :" + b2); System.out.println("Value of boolean variable b3 is :" + b3); } }

toString(): return the string representation of a boolean


The static method toString() returns the string representation of a boolean: public static String toString boolean)
public class MainClass {

public static void main(String[] args) { Boolean b = Boolean.valueOf("true"); System.out.println(b.toString()); } }

true

Using the boolean type


public class MainClass { public static void main(String args[]) { boolean b; b = false; System.out.println("b is " + b); b = true; System.out.println("b is " + b); // a boolean value can control the if statement if(b) System.out.println("This is executed."); b = false; if(b) System.out.println("This is not executed."); // outcome of a relational operator is a boolean value System.out.println("10 > 9 is " + (10 > 9)); } }

b is b is This 10 >

false true is executed. 9 is true

Boolean Variables
1. Variables of type boolean can have only one of two values, true or false. 2. The values 'true' and 'false' are boolean literals. 3.
public class MainClass{

public static void main(String[] arg){ boolean state = true; state = false; System.out.println(state); } }

false

Several assignment operators


public class MainClass { public static void main(String args[]) { int a = 1; int b = 2; int c = 3; a += 5; b *= 4; c += a * b; c %= 6; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); } }

a = 6 b = 8 c = 3

The instanceof Keyword


The instanceof keyword can be used to test if an object is of a specified type.
if (objectReference instanceof type)

The following if statement returns true.


public class MainClass { public static void main(String[] a) { String s = "Hello"; if (s instanceof java.lang.String) { System.out.println("is a String"); } }

is a String

However, applying instanceof on a null reference variable returns false. For example, the following if st returns false.
public class MainClass { public static void main(String[] a) { String s = null; if (s instanceof java.lang.String) { System.out.println("true"); } else { System.out.println("false"); } } }

false

Since a subclass 'is a' type of its superclass, the following if statement, where Child is a subclass of Pa returns true.
class Parent { public Parent() { } } class Child extends Parent { public Child() { super(); } } public class MainClass { public static void main(String[] a) { Child child = new Child(); if (child instanceof Parent) { System.out.println("true"); } } }

true

Identifying Objects
class Animal { public String toString() { return "This is an animal "; } } class Dog extends Animal { public void sound() { System.out.println("Woof Woof"); } } public class MainClass { public static void main(String[] a) { Dog aDog = new Dog(); if (aDog instanceof Animal) { Animal ani = (Animal) aDog; System.out.println(ani); } } }

This is an animal

Finding Out of what Class an Object is Instantiated


import java.util.ArrayList; import java.util.Vector; public class Main { public static void main(String[] args) { Object testObject = new Vector(); if (testObject instanceof Vector) System.out.println("Object was an instance of the class java.util.Vector"); else if (testObject instanceof ArrayList) System.out.println("Object was an instance of the class java.util.ArrayList"); else System.out.println("Object was an instance of the " + testObject.getClass()); } }

instanceof operator and class hierarchy


class A { int i, j;

} class B { int i, j; } class C extends A { int k; } class D extends A { int k; } class InstanceOf { public static void main(String args[]) { A a = new A(); B b = new B(); C c = new C(); D d = new D(); if (a instanceof A) System.out.println("a if (b instanceof B) System.out.println("b if (c instanceof C) System.out.println("c if (c instanceof A) System.out.println("c is instance of A"); is instance of B"); is instance of C"); can be cast to A");

if (a instanceof C) System.out.println("a can be cast to C"); System.out.println(); A ob; ob = d; // A reference to d System.out.println("ob now refers to d"); if (ob instanceof D) System.out.println("ob is instance of D"); System.out.println(); ob = c; // A reference to c System.out.println("ob now refers to c"); if (ob instanceof D) System.out.println("ob can be cast to D"); else System.out.println("ob cannot be cast to D"); if (ob instanceof A) System.out.println("ob can be cast to A"); System.out.println();

// all objects can be cast to Object if (a instanceof Object) System.out.println("a may be cast to if (b instanceof Object) System.out.println("b may be cast to if (c instanceof Object) System.out.println("c may be cast to if (d instanceof Object) System.out.println("d may be cast to } }

Object"); Object"); Object"); Object");

The for-each loop is essentially read-only


public class MainClass { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for(int x : nums) { System.out.print(x + " "); x = x * 10; // no effect on nums } System.out.println(); for(int x : nums) System.out.print(x + " "); System.out.println(); } }

What Is a Java Class?


class Employee { int age; double salary; }

Classes are the fundamental building blocks of a Java program. You can define an Employee class as

1. 2. 3. 4.

By convention, class names capitalize the initial of each word. For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator. This type of naming convention is known as Pascal naming convention. The other convention, the camel naming convention, capitalize the initial of each word, except th word. 5. Method and field names use the camel naming convention.

Fields 1. Fields are variables. 2. They can be primitives or references to objects. For example, the Employee class has two fields, age and salary.
public class Employee{ int age; int salary }

1. Field names should follow the camel naming convention. 2. The initial of each word in the field, except for the first word, is written with a capital letter. 3. For example: age, maxAge, address, validAddress, numberOfRows. Defining Classes: A class has fields and methods
public class MainClass { private int aField; public void aMethod() { } }

Creating Objects of a Class


class Sphere { double radius; // Radius of a sphere Sphere() { } // Class constructor Sphere(double theRadius) { radius = theRadius; // Set the radius } } public class MainClass { public static void main(String[] arg){ Sphere sp = new Sphere(); }

Checking whether the object referenced was of type String


class Animal { public Animal(String aType) { type = aType; } public String toString() { return "This is a " + type; } private String type; } public class MainClass { public static void main(String[] a) { Animal pet = new Animal("a"); if (pet.getClass() == Animal.class) { System.out.println("it is an animal!"); } } }

it is an animal!

Class declaration with one method


public class MainClass { public static void main( String args[] ) { GradeBook myGradeBook = new GradeBook(); myGradeBook.displayMessage(); } } class GradeBook { public void displayMessage() { System.out.println( "Welcome to the Grade Book!" ); } }

Welcome to the Grade Book!

Class declaration with a method that has a parameter


public class MainClass { public static void main( String args[] ) { GradeBook myGradeBook = new GradeBook(); String courseName = "Java "; myGradeBook.displayMessage( courseName ); } } class GradeBook { public void displayMessage( String courseName ) { System.out.printf( "Welcome to the grade book for\n%s!\n", courseName ); } } output

Welcome to the grade book for Java !

Class that contains a String instance variable and methods to set an its value
public class MainClass { public static void main( String args[] ) { GradeBook myGradeBook = new GradeBook(); System.out.printf( "Initial course name is: %s\n\n",myGradeBook.getCourseName() ); String theName = "Java"; myGradeBook.setCourseName( theName ); // set the course name myGradeBook.displayMessage(); } } class GradeBook {

private String courseName; // course name for this GradeBook // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // method to retrieve the course name public String getCourseName() { return courseName; } // display a welcome message to the GradeBook user public void displayMessage() { System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName() ); } }

Initial course name is: null Welcome to the grade book for Java!

Class with a constructor to initialize instance variables


public class MainClass { public static void main( String args[] ) { Account account1 = new Account( 50.00 ); // create Account object Account account2 = new Account( -7.53 ); // create Account object System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() ); double depositAmount; // deposit amount read from user depositAmount = 10.10; account1.credit( depositAmount ); // add to account1 balance System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() ); depositAmount = 12.12; account2.credit( depositAmount ); // add to account2 balance

System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n", account2.getBalance() ); } } class Account { private double balance; // instance variable that stores the balance // constructor public Account( double initialBalance ) { if ( initialBalance > 0.0 ) balance = initialBalance; } public void credit( double amount ) { balance = balance + amount; } public double getBalance() { return balance; } }

account1 balance: $50.00 account2 balance: $0.00 account1 balance: $60.10 account2 balance: $0.00 account1 balance: $60.10 account2 balance: $12.12

Specifying initial values in a class definition


class A { A(int marker) { System.out.println("Bowl(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } }

class B { static A a = new A(1); B() { System.out.println("Table()"); staticA.f(1); } void f2(int marker) { System.out.println("f2(" + marker + ")"); } static A staticA = new A(2); } class C { A a = new A(3); static A staticA = new A(4); C() { System.out.println("Cupboard()"); staticA.f(2); } void f3(int marker) { System.out.println("f3(" + marker + ")"); } static A staticA2 = new A(5); } public class MainClass { public static void main(String[] args) { System.out.println("Creating new Cupboard() in main"); new C(); System.out.println("Creating new Cupboard() in main"); new C(); t2.f2(1); t3.f3(1); } static B t2 = new B(); static C t3 = new C(); }

Bowl(1) Bowl(2) Table() f(1) Bowl(4) Bowl(5) Bowl(3)

Cupboard() f(2) Creating new Cupboard() in main Bowl(3) Cupboard() f(2) Creating new Cupboard() in main Bowl(3) Cupboard() f(2) f2(1) f3(1)

Using Constructors
1. 2. 3. 4. 5. 6. 7.

Every class must have at least one constructor. If there is no constructors for your class, the compiler will supply a default constructor(no-arg c A constructor is used to construct an object. A constructor looks like a method and is sometimes called a constructor method. A constructor never returns a value A constructor always has the same name as the class. A constructor may have zero argument, in which case it is called a no-argument (or no-arg, for constructor. 8. Constructor arguments can be used to initialize the fields in the object. The syntax for a constructor is as follows.
constructorName (listOfArguments) { [constructor body] } public class MainClass { double radius; // Class constructor MainClass(double theRadius) { radius = theRadius; } }

The Default Constructor


public class MainClass { double radius;

MainClass() { } // Class constructor MainClass(double theRadius) { radius = theRadius; } }

Multiple Constructors
class Sphere { int radius = 0; Sphere() { radius = 1; } Sphere(int radius) { this.radius = radius; } }

Calling a Constructor From a Constructor


class Sphere { int radius = 0; double xCenter; double yCenter; double zCenter; Sphere() { radius = 1; } Sphere(double x, double y, double z) { this(); xCenter = x; yCenter = y; zCenter = z; } Sphere(int theRadius, double x, double y, double z) {

this(x, y, z); radius = theRadius; } }

Duplicating Objects using a Constructor


class Sphere { int radius = 0; double xCenter; double yCenter; double zCenter; Sphere() { radius = 1; } Sphere(double x, double y, double z) { this(); xCenter = x; yCenter = y; zCenter = z; } Sphere(int theRadius, double x, double y, double z) { this(x, y, z); radius = theRadius; } // Create a sphere from an existing object Sphere(final Sphere oldSphere) { radius = oldSphere.radius; xCenter = oldSphere.xCenter; yCenter = oldSphere.yCenter; zCenter = oldSphere.yCenter; } }

Class Initializer: during declaration


// ClassInitializer2.java class ClassInitializer2 { static boolean bool = true; static byte by = 20; static char ch = 'X';

static static static static static static

double d = 8.95; float f = 2.1f; int i = 63; long l = 2L; short sh = 200; String str = "test";

public static void main(String[] args) { System.out.println("bool = " + bool); System.out.println("by = " + by); System.out.println("ch = " + ch); System.out.println("d = " + d); System.out.println("f = " + f); System.out.println("i = " + i); System.out.println("l = " + l); System.out.println("sh = " + sh); System.out.println("str = " + str); } }

Order of constructor calls


class Meal { Meal() { System.out.println("Meal()"); } } class Bread { Bread() { System.out.println("Bread()"); } } class Cheese { Cheese() { System.out.println("Cheese()"); } } class Lettuce { Lettuce() { System.out.println("Lettuce()"); } } class Lunch extends Meal { Lunch() { System.out.println("Lunch()"); } } class PortableLunch extends Lunch {

PortableLunch() { System.out.println("PortableLunch()"); } } class Sandwich extends PortableLunch { private Bread b = new Bread(); private Cheese c = new Cheese(); private Lettuce l = new Lettuce(); public Sandwich() { System.out.println("Sandwich()"); } } public class MainClass { public static void main(String[] args) { new Sandwich(); } }

Meal() Lunch() PortableLunch() Bread() Cheese() Lettuce() Sandwich()

You might also like