1)How to create a project in eclipse?
1)How to create a project in eclipse?
- A java package is a group of similar types of classes, interfaces and sub-packages.
- Package in java can be categorized in two form, built-in package and user-defined package.
- There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
- Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package :
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Built in Packages:
How to access package from another package?
There are three ways to access the package from outside the package.
- import package.*;
- import package.classname;
- fully qualified name.
step1)First create a java project
Step2)Expand the project name under package explorer by clicking the arrow mark before projectname <projectname
NOTE: if you want to create new package under src folder, everytime you need to follow step4 to step6
step1)select the package under src folder of the java project
First Java Program:
Java "Hello, World!" Program
// Your First Program
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output
Hello, World!
How Java "Hello, World!" Program Works?
// Your First Program
In Java, any line starting with//
is a comment. Comments are intended for users reading the code to understand the intent and functionality of the program. It is completely ignored by the Java compiler (an application that translates Java program to Java bytecode that computer can execute). To learn more, visit Java comments.class HelloWorld { ... }
In Java, every application begins with a class definition. In the program, HelloWorld is the name of the class, and the class definition is:class HelloWorld { ... .. ... }
For now, just remember that every Java application has a class definition, and the name of the class should match the filename in Java.public static void main(String[] args) { ... }
This is the main method. Every application in Java must contain the main method. The Java compiler starts executing the code from the main method.
int a
and int b
variables, and main
and pi
methods?"JAVA PROGRAM STRUCTURE:
Java Class
A class is a blueprint for the object. Before we create an object, we first need to define the class.
We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
Since many houses can be made from the same description, we can create many objects from a class.
Class contains many members variables, methods, constructors and blocks.
Class is a logical entity
class syntax
accessmodifier class classname{
fields/variables
methods
constructors
blocks
}
Create a class in Java
We can create a class in Java using the class keyword. For example,
class ClassName {
// fields
// methods
}
Here, fields (variables) and methods represent the state and behavior of the object respectively.
- fields are used to store data
- methods are used to perform some operations
For our bicycle object, we can create the class as
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
In the above example, we have created a class named Bicycle. It contains a field named gear and a method named braking().
Here, Bicycle is a prototype. Now, we can create any number of bicycles using the prototype. And, all the bicycles will share the fields and methods of the prototype
What are Access Modifiers?
In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods, constructors, data members, and the setter methods. For example,
class Animal {
public void method1() {...}
private void method2() {...}
}
In the above example, we have declared 2 methods: method1() and method2(). Here,
- method1 is
public
- This means it can be accessed by other classes. - method2 is
private
- This means it can not be accessed by other classes.
- Default – No keyword required
- Private
- Protected
- Public
There are four access modifiers keywords in Java and they are:
Modifier | Description |
Default | declarations are visible only within the package (package private) |
Private | declarations are visible within the class only |
Protected | declarations are visible within the package or all subclasses |
Public | declarations are visible everywhere |
Public Access Modifier
When methods, variables, classes, and Constructors are declared public
, then we can access them from anywhere. The public access modifier has no scope restriction. For example,
When you update your Facebook Status, it gives you 4 options
1. If you make this status visible for Public, anyone can see this status on Internet (Anyone On or Off Facebook). [Public Access Specifiers]
// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;
// public method
public void display() {
System.out.println("This is an animal class - display()");
System.out.println("Animal have " + legCount + " legs.");
}
}
// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();
// accessing the public variable
animal.legCount = 4;
// accessing the public method
animal.display();
}
}
Output:
This is an animal class - display().
Animal have 4 legs.
Here,
- The public class Animal is accessed from the Main class.
- The public variable legCount is accessed from the Main class.
- The public method
display()
is accessed from the Main class.
Default Access Modifier
If we do not explicitly specify any access modifier for classes, methods, variables, and Constructors then by default the default access modifier is considered.
If you make this status visible for "Friends", then your status will be only visible for your Friends. Not your friends friends or everyone presents on Facebook. [Default Access Specifiers]
For example,
package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}
Private Access Modifier
When variables, Constructors, and methods are declared private
, they cannot be accessed outside of the class. class can't be declared private.
If you make this status visible "only for me". No one can see this status except you. [Private Access Specifiers]
For example,
class Data {
// private variable
private String name;
}
public class Main {
public static void main(String[] main){
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "qaautomation";
}
}
In the above example, we have declared a private variable named name. When we run the program, we will get the following error:
Main.java:18: error: name has private access in Data
d.name = "qaautomation";
^
The error is generated because we are trying to access the private variable of the Data class from the Main class.
Protected Access Modifier
When methods, Constructors, and data members are declared- protected
, we can access them within the same package as well as from subclasses.
If you make this status visible for Friends or Friends of friends, then your status will be only visible for your friends and your friends friends. Not everyone presents on Facebook or Internet. [Protected Access Specifiers]
For example,
class Animal {
// protected method
protected void display() {
System.out.println("This is an animal class method -display");
}
}
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
}
}
In the above example, we have a protected method named
display()
inside the Animal class. The Animal class is inherited by the Dog class. To learn more about inheritance.We then created an object dog of the Dog class. Using the object we tried to access the protected method of the parent class.
Since protected methods can be accessed from the child classes, we are able to access the method of Animal class from the Dog class.
Note: We cannot declare classes or interfaces
protected
in Java
Access modifiers are mainly used for encapsulation. It can help us to control what part of a program can access the members of a class. So that misuse of data can be prevented.
If one object changes the value of the static variable, it will reflect in other objects too.
We can also access the static variables without creating an object for that class. Static variables are the first ones which are loaded into the memory when a class is loaded.
Suppose, you are working in say, A company. Certainly, a number of employees are working there too. All these employees have a different identity(name,age,address etc) but all share the same company name.
Here, if you do not declare the company name as static then all objects take it as an instance variable and allocate some memory. if there are n number of objects then memory space allocated=no_of_object*space allocated by one instance variable(company name).
So, make it static then it is shared by all objects from the same memory location and it helps to reduce memory also.
Example 2:
To illustrate, consider a class that models a Car. Cars have engines. But no two cars share the same engine (simultaneously). This means that each car has an engine that belongs to it exclusively. Therefore, an engine in a Car class would be a non-static attribute of the class. HOWEVER, the brand name of a car is shared across all instances of a class. In this case, brandName (i.e. Chevrolet) should be shared across all Car instances. Now, here’s the WHY you want to do this. Suppose tomorrow Chevrolet is bought by Ford. By making the brandName shareable (static) across all instances of Car, every instance of Car can be rebranded to Ford by making a single change. Because this is a shareable attribute, all instances receive the change without having to go to each individual instance to make the same change.
Example 3:
let's see through an example
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.
class Student{
int rollno;
String name;
static String college ="ITS”;
Student(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student s1 = new Student8(111,"Karan");
Student s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
The first one is a constant variable such as PI, application name, or label. In example, you can see that Math.PI is a static variable provided by Java. In this case, we need to declare it with the “final” keyword.
- public class Math {
- public static final float PI = 3.14;
- }
The second one is a variable that can be changed but it is the only one in your application. Normally, it is a counter which is used to count something like clicked times or the total number of transactions.
- public class Bank {
- public static long NUMBER_OF_TRANSACTIONS = 0;
- }
Static Blocks in Java
Generally, static blocks in Java are used to initialize static variables. They are executed only once when the class is loaded and hence, are perfect for this job. Also, you can include more than one static block in the class. Static blocks can only access static variables. Let’s understand static blocks using the below example.
class Test{
static int i = 10;
static int j;
static{
System.out.println("Initializing the Static Variable using Static Block ...");
j = i * 5;
}
}
class Main{
public static void main(String args[]){
System.out.println("Value of i is: " + Test.i);
System.out.println("Value of j is: " + Test.j);
}
Here, you saw the creation of two static variables called i and j inside the Test class. It went on to initialize variable j using a static block. In the main method, you must use the class name to print the values of i and j static variables. You can see that the static block gets executed before the execution of the main method. When the static block is executed, it prints the first line regarding the initialization and then initializes the variable j. Then, the main method gets executed which prints the values of both variables.
public static void main(String[] args)
Each part of this method signature has a specific role:
- public: The method is accessible from anywhere.
- static: The method can be called without creating an instance of the class.
- void: The method does not return any value.
- main: The name of the method that Java looks for as the starting point of the application.
- String[] args: The parameter that allows the method to accept command-line arguments.
What Happens If static
Is Removed?
If you remove the static
keyword from the main
method, like this:
javapublic void main(String[] args)
The following issues occur:
No Entry Point: The Java Virtual Machine (JVM) expects to find a
main
method with the exact signaturepublic static void main(String[] args)
. Withoutstatic
, the method is not recognized as the entry point for the application. Consequently, the JVM will not be able to start the application and will throw an error.Instance Method: The method becomes an instance method. This means you would need an instance of the class to invoke it. However, since the JVM requires a static
main
method to initiate the program, it will never reach the point of creating an instance to call this non-static method.Error Message: When you try to run a Java application with a non-static
main
method, you will encounter an error like this:plaintextError: Main method not found in class <YourClass>, please define the main method as: public static void main(String[] args)
println
doesn't start printing text from a new line. It prints text on the current line, but makes it so the next text will be printed on a new line."println()
command prints the text on the screen and adds a special unseen 'newline character'. This is what makes the next text start on a new line."System.out.print()
command, the text is displayed on the same line.Commands | What will be displayed on the screen | |
---|---|---|
1 | Amigo Is The Best | |
2 | AmigoIs The Best | |
3 | AmigoIs TheBest |
Command | Description (what it does) |
---|---|
Displays the number 1 on the screen | |
Displays "Amigo" on the screen | |
Displays "Rishi & Amigo" on the screen |
1)What is
a class & give class structure?
2)What is
the naming conventions of a clsss?
3)Which
accessmodifier keywords are applicable for class?
4)what is
Modifier?
5)What are
different types of Modifiers?
6)What is AccessModifier? And what are different
types of accessmodifiers and explain in detail?
7)what is main()
structure?
8)what is
meant by static keyword?explain in detail?
9) what is
static variable syntax?
10)what is
static method syntax without parameters?
11)what is
static block syntax?
12)what is
void? Explain different type of method syntaxes?
13)why
main() made it as static?
14)what is
the naming conventions of a method?
15)What are
different types of main() arguments?
16)Explain each
word in System.out.println() in detail?
17)what is
the difference between println() and print()?
18)what are
different types of System class variables?
19)Guess the output
package basics;
public class Test {
public static void main(String[] args) {
int Integer=20;
char String = 'C';
System.out.print(Integer);
System.out.println(String);
}
}
i)20C
ii)Exception
-------------------
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.