JAVA

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

When an object contains another object as its attribute,

, we have an aggregation between them. It is termed as "has-a" relationship.

Show an example of a Java interface

// A simple interface interface Player { final int id = 10; int move(); }

Methods can be called or invoked to execute its statements. Methods may also return results after execution. The return keyword is used to return a value It also sends back the flow of execution from a method to the calling method If a method does not return anything, the return type should be specified as void To execute a method, it needs to be called. A method call (invocation) statement in a program looks like this:

// Calling getPriceAfterDiscount() method in the same class float finalPrice = getPriceAfterDiscount(12); // Here 12 is the actual argument Here the value returned by the method will be stored in the variable finalPrice. The arguments passed in the method call statement are called actual arguments or parameters. Remember the main() method! ...It is the starting point for the execution of all the programs.

A full example of how a java class should look.

// Class Declaration public class Dog { // Instance Variables String name; String breed; int age; String color; // Constructor Declaration of Class public Dog(String name, String breed, int age, String color) { this.name = name; this.breed = breed; this.age = age; this.color = color; } // method 1 public String getName() { return name; } // method 2 public String getBreed() { return breed; } // method 3 public int getAge() { return age; } // method 4 public String getColor() { return color; } @Override public String toString() { return("Hi my name is "+ this.getName()+ ".\nMy breed,age and color are " + this.getBreed()+"," + this.getAge()+ ","+ this.getColor()); } public static void main(String[] args) { Dog tuffy = new Dog("tuffy","papillon", 5, "white"); System.out.println(tuffy.toString()); } }

the default value for int in Java is

0

Basics of using eclipse

1. Make sure your workspace is set up. 2. If your work space is damaged you need to make a new on 3. Import the files that you want to work with.

A few other built-in annotations:

@Deprecated denotes a method as obsolete. A warning occurs when such a method is used @SuppressWarnings(value="unused") prevents warnings related to unused local variables and unused private methods. Here value is an element

Structure of Java files

A single .java file can have multiple classes, but they are compiled into their own separate .class files. It is a good practice to have a single Java class in a .java file. The class containing the main method must be public. The .java file should have the same name as that of the public class. There can be only one public class in a .java file.

We have just seen that we can have methods as follows: public static void showCustomerDetails(Customer customer) { customer.displayDetails(); }

And dynamic binding allows this method to work with any object of type Customer or its child. This is required because until runtime, we cannot know what kind of customer will come. If the customer is a regular customer, the customer in our method behaves like a RegularCustomer. If the customer is a premium customer, it behaves like a PremiumCustomer. Since customer can behave like multiple objects, it is said to exhibit polymorphism. And since this can happen only at runtime, it is called dynamic polymorphism. Remember overloading? It allows multiple methods to have the same name. It appears as if the same method behaves differently in different situations. This is also polymorphism. Since calls to overloaded methods can be resolved based on the method signatures, the binding happens at compile time itself. And hence called static polymorphism.

How to setup tomcat apache in eclipse

Click Server Click Runtime Environments Click Add Select your version of Tomcat (Probably 7) Locate the Tomcat directory on your computer

What happens in a spring MVC request and response

DispatcherServlet intercepts the incoming requests and passes them on to the HandlerMapping. HandlerMapping maps the request to appropriate Controller. The Controller takes the request and calls the appropriate service methods. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request.

JSP pages are just like

ERB pages in ruby

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size byte -> short -> char -> int -> long -> float -> double Narrowing Casting (manually) - converting a larger type to a smaller size type double -> float -> long -> int -> char -> short -> byte

Numbers Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte, short, int and long. Which type you should use, depends on the numeric value. Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double. Even though there are many numeric types in Java, the most used for numbers are int (for whole numbers) and double (for floating point numbers). However, we will describe them all as you continue to read.

Java is platform independent

It will run without recompilation on all OS systems

Java interface

Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how. It is the blueprint of the class. An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement. If a class implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract. A Java library example is, Comparator Interface. If a class implements this interface, then it can be used to sort a collection. Syntax :

Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects. The main difference between primitive and non-primitive data types are: Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String). Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot. A primitive type has always a value, while non-primitve types can be null. A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter. The size of a primitive type depends on the data type, while non-primitive types have all the same size. Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You will learn more about these in a later chapter.

In Java there are two types of datatypes

Primitive and Non-Primitive; Primitive hole the value of the data in them where as non-primitive has a reference to memory location

In the above code we are using the setProductId() method to access the private attribute productId of product p1. If we look into the class, setProductId() itself accesses the instance variable productId to set its value.

Product p1 = new Product(); p1.setProductId(101);

In Java, an object is created using the new keyword. An E-Mart product can be created as follows

Product prodObj = new Product(); // Creating a product object

A class can have multiple constructors to initialize different number of fields. This is called constructor overloading

Product { // Attributes and methods Product() { } Product(int id, String name) { } Product(int id, String name, float price, int stock) { } }

A class can have multiple constructors to initialize different number of fields. This is called constructor overloading.

Product { // Attributes and methods Product() { } Product(int id, String name) { } Product(int id, String name, float price, int stock) { } } how you invoke the objects will tell which constructor will be called

You can also use the concat() method to concatenate two strings

String firstName = "John "; String lastName = "Doe"; System.out.println(firstName.concat(lastName));

The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes:

String greeting = "Hello World"; System.out.println(greeting);

Create a variable called name of type String and assign it the value "John"

String name = "John"; System.out.println(name);

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

String txt = "Please locate where 'locate' occurs!"; System.out.println(txt.indexOf("locate")); // Outputs 7

Byte

The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other integer types to save memory when you are certain that the value will be within -128 and 127: byte myNum = 100; System.out.println(myNum);

Int

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int data type is the preferred data type when we create variables with a numeric value

Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an "L":

What does the super method do in JAVA?

The parent constructors in an inheritance hierarchy are automatically invoked because of the implicit usage of the super keyword. The super keyword is used to refer to the parent class. This is what happens (can be done explicitly as well): class RegularCustomer extends Customer { public RegularCustomer() { super(); // Invoking the parent class constructor System.out.println("It is a regular customer!"); } } If we want to invoke a parameterized constructor of the parent class, we need to pass the required parameters in the super keyword. Here's an example involving the employees of E-Mart: class EMartEmployee { // Instance variables and methods public EMartEmployee(String name, float salary) { // Parent class constructor this.name = name; this.salary = salary; } } class EMartManager extends EMartEmployee { private float bonus; public EMartManager(String name, float salary, float bonus) { // Child class constructor super(name, salary); this.bonus = bonus; } } If the parent class has only a parameterized constructor, the child must call it using super. Also, the call to a super constructor has to be the first statement inside a constructor. We will look at more uses of the super keyword later.

Use float or double?

The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

What is servlet?

The servlet is a Java programming language class used to process client requests and generate dynamic web content. Servlets are mostly used to process or store data submitted by an HTML form, provide dynamic content and manage state information that does not exist in the stateless HTTP protocol.

Short

The short data type can store whole numbers from -32768 to 32767:

Create a Java Servlet in Eclipse

This is how you create a Java Servlet step-by-step: Right click on your code directory in the Eclipse Project Explorer Click New then Project Click Dynamic Web Project Give it a name (mine is Lesson41) then click Finish Right click on the Java Resources directory Select New and then Servlet Enter a Package Name (mine is helloservlets) Enter a Class Name (mine is Lesson41) Click Next and Finish Edit the doGet method (My Code is Below) Change the web.xml file (My Code is Below) Right click on the project and select Run on Server

Find out the difference between soap based

and restful based webservises

Booleans A boolean data type is declared with the boolean keyword and can only take the values true or false:

boolean isJavaFun = true; boolean isFishTasty = false; System.out.println(isJavaFun); // Outputs true System.out.println(isFishTasty); // Outputs false

What are the Java primitive types?

boolean, char, byte, short, int, long, float, double

a java file cannot contain 2 public classes

but it can contain multiple classes just as long as they are not public

Alternatively, you can use ASCII values to display certain characters:

char a = 65, b = 66, c = 67; System.out.println(a); System.out.println(b); System.out.println(c);

Characters The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c':

char myGrade = 'B'; System.out.println(myGrade);

hasNextInt()

checks to see if there are more ints this method

In Java all datatypes have to be declared

class AverageSales { public static void main(String[] args) { int sum = 0, count = 0; int[] sales = { 6, 9, 7, 10, 11, 9, 7, 12, 14, 15, 13, 11 }; for (int index = 0; index < sales.length; index++) { sum += sales[index]; } float average = (float) sum / sales.length; for (int sale : sales) { if (sale > average) count++; } System.out.println("Average sale: " + average); System.out.println("Sales above average: " + count); } }

Car class in JAVA

class Car { private float speed; // private prevents direct access public void accelerate(float speedToAdd) { // Method to increase speed this.speed += speedToAdd; if(this.speed > 120) this.speed = 120; // Limiting speed to 120 kmph } // Other fields and methods } This would need a getter method

Actually, the super keyword can be used to refer to any non-private members of a parent in a hierarchy. This facilitates reusability of existing functionalities. Apart from accessing the parent class constructors and methods which have been overridden in the child class, super keyword can also be used to access instance variables (non-private) of the parent class when both the parent and child classes have variables with the same name. Here's an example:

class EMartEmployee { protected float salary; // Other fields and methods } class EMartManager extends EMartEmployee { private float salary; private float bonus; public void calculateSalary() { this.salary = super.salary + bonus; } }

example of overloading

class MethodOverloadingTester { // Method to find the area of circle public float calculateArea(float a) { float radius = a; return 3.14f*radius*radius; } // Method to find the area of rectangle public float calculateArea(float a, float b) { return a*b; } //pass different arguments to test the overloaded methods public static void main(String[] args) { MethodOverloadingTester test = new MethodOverloadingTester(); float circleArea = test.calculateArea(1.7f); float rectangleArea = test.calculateArea(2.5f, 3.4f); System.out.println("Area of circle: " + circleArea); System.out.println("Area of Rectangle: " + rectangleArea); } }

We have covered the basics of OOP while discussing E-Mart's Product class. Before we dive into the advanced OOP concepts, here is the complete Product class for a quick look:

class Product { /* Instance variables or attributes */ private int productId; private String name; private float price; private int stock; /* static variable for autogenerating productId */ private static int idCounter = 100; /* Parameterized constructor to initialize attributes during instantiation */ public Product(String name, float price, int stock) { this.productId = ++idCounter; this.name = name; this.price = price; this.stock = stock; } public float getPriceAfterDiscount(int discountPercentage) { float discountedPrice = price - (price * discountPercentage / 100); return discountedPrice; } /* Overloaded methods to display product details for employees and customers respectively */ public void displayDetails() { System.out.println("Product Id: " + productId); System.out.println("Product Name: " + name); System.out.println("Product Price: " + price); System.out.println("Stock: " + stock); } public void displayDetails(int discountPercentage) { System.out.println("Product Name: " + name); System.out.println("Discounted price: " + getPriceAfterDiscount(discountPercentage)); if(stock > 0) System.out.println("In stock"); else System.out.println("Out of stock!"); } /* Getters and setters */ public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } }

this keyword is also used for invoking one constructor from another constructor. This helps in reusing constructor logic.

class Product { // Fields and methods public Product(int productId, String name) { this.productId = productId; this.name = name; } public Product(int productId, String name, float price, int stock) { this(productId, name); // Invoking overloaded constructor this.price = price; this.stock = stock; } } You don't need to rewrite portions of methods

In Java shared attributes must have the static keyword

class Product { private int productId; private String name; private float price; private int stock; private static int idCounter = 100; public Product(String name, float price, int stock) { this.productId = ++idCounter; this.name = name; this.price = price; this.stock = stock; } // Other methods }

Q to ask 1 "Why am I printing out X"

class Test { public static void main(String[] args) { // Understanding implicit conversion int i = 50; // implicit type conversion long l = i; // implicit type conversion float f = l; System.out.println("Int value "+i); System.out.println("Long value "+l); System.out.println("Float value "+f); // Uncomment the code to understand the need for explicit conversion char ch = 'c'; int num = 88; ch = (char)num; System.out.println(ch + "Here"); } }

The double data type can store fractional numbers from 1.7e−308 to 1.7e+038. Note that you should end the value with a "d":

double myNum = 19.99d; System.out.println(myNum);

There are multiple way to declare something as a float (Java)

example 5.0 or (float)5 or 5F

abstract class Customer { private int customerId; private String password; private String name; private String phone; private Address address; public float orderProducts(Product[] products) { BillCalculator billCalc = new BillCalculator(); billCalc.processOrder(products); return billCalc.getAmount(); } public abstract void displayDetails(); // Getters and setters }

final class RegularCustomer extends Customer { public RegularCustomer(int id, String name, String password, String phone, Address address) { this.setCustomerId(id); this.setName(name); this.setPassword(password); this.setPhone(phone); this.setAddress(address); } @Override public void displayDetails() { System.out.println("Customer Id: " + this.getCustomerId()); System.out.println("Customer Name: " + this.getName()); System.out.println("Customer phone: " + this.getPhone()); } @Override public float orderProducts(Product[] products) { float billAmount = super.orderProducts(products); return billAmount * 0.95f; // Applying 5% discount } } final class PremiumCustomer extends Customer implements MembershipCardHolder { private int points = DEFAULT_POINTS; public PremiumCustomer(int id, String name, String password, String phone, Address address) { this.setCustomerId(id); this.setName(name); this.setPassword(password); this.setPhone(phone); this.setAddress(address); } @Override public void displayDetails() { System.out.println("Customer Id: " + this.getCustomerId()); System.out.println("Customer Name: " + this.getName()); System.out.println("Customer phone: " + this.getPhone()); System.out.println("Points remaining: " + this.points); } @Override public float redeemPoints(int pointsToRedeem) { pointsToRedeem = pointsToRedeem > this.points ? this.points : pointsToRedeem; float amountToRedeem = pointsToRedeem * 0.5f; // Point value is Rs. 0.5 this.points = this.points - pointsToRedeem; return amountToRedeem; } @Override public void addPoints(float money) { this.points += (int) money / 100; // Point cost is Rs. 100 } @Override public float orderProducts(Product[] products) { float billAmount = super.orderProducts(products); float finalAmount = billAmount * 0.90f; // Applying 10% discount addPoints(finalAmount); return finalAmount; } public float orderProducts(Product[] products, int pointsToRedeem) { float billAmount = super.orderProducts(products); float finalAmount = billAmount * 0.90f; // Applying 10% discount if(finalAmount != 0) finalAmount -= redeemPoints(pointsToRedeem); // Redeeming points addPoints(finalAmount); return finalAmount; } }

A floating point number can also be a scientific number with an "e" to indicate the power of 10:

float f1 = 35e3f; double d1 = 12E4d; System.out.println(f1); System.out.println(d1);

Float The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an "f":

float myNum = 5.75f; System.out.println(myNum);

So far we have been using "public" and "private" members in our code to provide different levels of access. These keywords are called access specifiers. They are used to specify access levels to control the visibility of a class and its members. This facilitates encapsulation. There are 4 such access levels in Java:

https://lex.infosysapps.com/viewer/lex_19179202633144730000/lex_9695157049697880000

Basic if else ladder in Java

if (<condition 1>) { <statements>; } else if (<condition 2>) { <statements>; } else { <statements>; }

Basic nested if in Java

if (<condition 1>) { if (<condition 2>) { <statements>; } else { <statements>; } }

Basic if else in Java

if (<condition>) { <statements>; } else { <statements>; }

What is the scanner input?

import java.util.Scanner; Scanner input = new Scanner(System.in); //where input is the variable

Java static methods cannot access

instance variables.

Implicit conversion happens when a value of smaller data type needs to be used as a value of larger compatible data type. Also called widening conversion, it is done automatically by Java. It follows the sequence below

int intValue = 1002; long longVariable = intValue; the Java program does this automatically

Generates random numbers between 0 to 9 in java

int randomNumber = (int) (Math.random() * 10); System.out.println("A random number " + randomNumber)

While declaring variables, we have to specify the kind of data they will hold

int sum = 0;

To declare more than one variable of the same type, use a comma-separated list:

int x = 5, y = 6, z = 50; System.out.println(x + y + z);

finally block

is a block of code that will run no matter what happens

Everything inside an interface is final meaning

it cannot change. It is basically a constant

JEE stands for

java enterprise edition: all of java and it's libraries included

Explicit conversions are generally used to prevent data loss in mathematical operations. Also, when a value of larger data type needs to be stored as a value of smaller data type, despite the possibility of data loss, we should explicitly specify the conversion. In such a case, it is called narrowing conversion. Example: While assigning a long variable to that of int type, we need to explicitly type cast:

long regId = 4567L; int iRegId = (int)regId; // Explicit Type Casting //or float percentage = ((float)totalMarks/800) * 100; // Explicit Type Casting

Look up dynamic binding

polymorphism

Static blocks are used to initialize static variables when it cannot be done in a single line. They can also be used to add preprocessing if required. Static blocks get executed once when a class gets loaded. If there are multiple static blocks, they will be executed in the order of their occurrence. Our product id counter can be initialized like this as well:

private static int idCounter; static { // Static block int randomNumber = 31; idCounter = (int) Math.pow(randomNumber, 3); // Initializing counter }

Once created, the object's methods can be invoked using the "." operator:

prodObj.setProductId(101); // Setting attribute values prodObj.setName("T-Shirt"); prodObj.setPrice(799f); String name = prodObj.getName(); // Getting attribute value float finalPrice = prodObj.getPriceAfterDiscount(12);

explain JAVA method overloading

product.displayDetails(); // Displaying all the product details for the employees product.displayDetails(5); // Displaying the discounted product details for customers where a different type of method with the same name will be called based on the number of arguments passed in

show an example of increment in java

public class MyClass { public static void main(String[] args) { int x = 5; ++x; System.out.println(x); } }

show an example decrement in java

public class MyClass { public static void main(String[] args) { int x = 5; --x; System.out.println(x); } }

The main() method is required and you will see it in every Java program:

public static void main(String[] args)

System.out.println() Inside the main() method, we can use the println() method to print a line of text to the screen:

public static void main(String[] args) { System.out.println("Hello World"); }

Basic switch statements in Java

switch (variable) { // The program flow jumps to the case which matches this variable's value case value1: <statements>; break; // breaks out of the switch block. Placed at the end of a case case value2: <statements>; break; default: <statements>; // Executes when none of the cases match }

Exceptions are errors

that occur at run-time which are essentially runtime errors. You can put different logic in exceptions

java has a math library

that you may or may not have to import

Static variables are class level variables which are used to keep a value across all the instances of a class. They are initialized when the class gets loaded (e.g. idCounter).

they are initialized when the class get loaded

Access specifiers help in limiting access to the members of a class. private members are accessible only inside their class, but public members are accessible in other classes as well. More about access specifiers will be discussed later

to be specified

In an interface

you have to use all of the methods when it is implemented but in abstract class you don't have to


Kaugnay na mga set ng pag-aaral

Texas Real Estate License Exam Prep

View Set